不同的Java Scanner用于输入不同类型
想象一下下面的scanario:我有一个程序要求输入一个整数,然后是一个String输入。
int age=0; String name; Scanner sc = new Scanner(System.in); System.out.print("Enter Age: "); age = sc.nextInt(); System.out.print("Enter Name: "); name= sc.nextLine();
使用aobe代码,我没有机会输入名称。 所以通常我会声明2个扫描仪对象,如下所示:
int age=0; String name; Scanner sc = new Scanner(System.in); Scanner sc2 = new Scanner(System.in); //2nd Scanner object System.out.print("Enter Age: "); age = sc.nextInt(); System.out.print("Enter Name: "); name= sc2.nextLine(); //Using 2nd Scanner Object
我的问题是:是否有必要声明多个扫描仪对象接受不同类型的输入? 我是否以正确的方式行事?
多年来我已经记住了这个问题。 (SO中的几个问题提到了多个扫描仪,但他们的问题只使用了一个扫描仪对象,所以我今天就问这个。)
@skiwi只使用一台Scanner
是正确的,所以你做得对。 它不起作用的原因是nextInt()
消耗构成整数的所有字符,但它不接触行尾字符。 因此,当nextLine()
时,它会看到行尾字符之前没有字符,因此它认为输入了一个空行,然后返回一个空字符串。 但是, nextLine()
确实使用了行尾字符,所以如果你调用sc.nextLine();
一旦你做name = sc.nextLine();
,它应该工作。
每个要扫描的对象应该只使用一个Scanner
实例。 在这种情况下,您正在从System.in
读取,因此同时在同一个上打开两个扫描仪甚至没有意义。
所以你肯定想要第一个选择,那么问题来了,它有什么问题:
好吧,你要求sc.nextInt()
,一个整数,而名字很少是一个整数。 您最有可能为一个单词寻找name = sc.nextLine()
或为整个句子寻找name = sc.nextLine()
(直到按下回车键)。
还要注意,在sc.nextInt()
,实际上在任何sc.next***()
,你需要按Enter键 。
您没有机会输入名称,因为nextInt()
不会读取换行符'\n'
(按Enter键后由用户输入 ),而nextLine()
。 所以只要你调用name = sc.nextLine();
,它只会读取nextInt()
没有读过的'\n'
字符。
如果您正在扫描相同的东西(如System.in
),则绝对不要创建新的扫描仪 – 如果您正在扫描其他内容(如不同的文件或其他内容),则只更改扫描仪。
要使代码正常工作(只有一个Scanner实例),请使用:
int age = 0; String name; Scanner sc = new Scanner(System.in); System.out.print("Enter Age: "); age = sc.nextInt(); System.out.print("Enter Name: "); sc.nextLine(); // "dispose" of the '\n' character // so that it is not recorded by the next line name = sc.nextLine(); // print your findings System.out.println("------\nAge: " + age + "\nName: " + name);
输入/输出示例:
Enter Age: 17 Enter Name: Michael ------ Age: 17 Name: Michael
您还可以使用:
name = sc.next();