使用扫描仪读取下一行的顺序有问题
Trouble with order of reading next line with Scanner
我正在使用 'Scanner' 做一些基本的 java 程序。我读了 Integer、Double 和 String。
我在将字符串扫描器与其他扫描器(如 int 和 double)一起使用时遇到一些问题。
声明部分:
Scanner scan = new Scanner(System.in);
int i2;
double d2;
String s2;
订单 #1:
i2 = scan.nextInt();
d2 = scan.nextDouble();
s2 = scan.nextLine();
结果:
编译器等待获取 i2 和 d2 的输入,但不等待 s2 的输入。它立即执行 s2 = scan.nextLine();
之后的行。当我调试时,s2 是空的。
订单#2:
i2 = scan.nextInt();
s2 = scan.nextLine();
d2 = scan.nextDouble();
结果:
这次编译器等待获取 i2 和 s2 的输入。当我输入 hello
时,它会抛出一个错误。
1
hello
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at HelloWorld.main(HelloWorld.java:18)
订单#3:
s2 = scan.nextLine();
i2 = scan.nextInt();
d2 = scan.nextDouble();
结果:
工作正常!!
那么为什么顺序在这里起作用?
尝试调用 next()
而不是 nextLine()
来读取字符串。
执行中的差异,订单变化,是由于新线 是 而不是 由 nextInt()
、nextDouble()
、next()
或 nextFoo()
方法使用。
因此,无论何时您在任何这些方法之后调用 nextLine()
,它都会消耗 newline,并且实际上跳过了该语句。
修复很简单,不要在 nextLine()
之前使用 nextFoo()
方法。尝试:-
i2 = Integer.parseInt(scan.nextLine());
d2 = Double.parseDouble(scan.nextLine());
s2 = scan.nextLine();
否则,您可以使用 new-line by
i2 = scan.nextInt();
d2 = scan.nextDouble();
scan.nextLine(); //---> Add this before the nextLine() call
s2 = scan.nextLine();
Order#3 工作正常,因为 nextLine()
是第一个语句,因此,有 no 剩余 个字符供消耗。
相关:Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
我正在使用 'Scanner' 做一些基本的 java 程序。我读了 Integer、Double 和 String。
我在将字符串扫描器与其他扫描器(如 int 和 double)一起使用时遇到一些问题。
声明部分:
Scanner scan = new Scanner(System.in);
int i2;
double d2;
String s2;
订单 #1:
i2 = scan.nextInt();
d2 = scan.nextDouble();
s2 = scan.nextLine();
结果:
编译器等待获取 i2 和 d2 的输入,但不等待 s2 的输入。它立即执行 s2 = scan.nextLine();
之后的行。当我调试时,s2 是空的。
订单#2:
i2 = scan.nextInt();
s2 = scan.nextLine();
d2 = scan.nextDouble();
结果:
这次编译器等待获取 i2 和 s2 的输入。当我输入 hello
时,它会抛出一个错误。
1
hello
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at HelloWorld.main(HelloWorld.java:18)
订单#3:
s2 = scan.nextLine();
i2 = scan.nextInt();
d2 = scan.nextDouble();
结果: 工作正常!!
那么为什么顺序在这里起作用?
尝试调用 next()
而不是 nextLine()
来读取字符串。
执行中的差异,订单变化,是由于新线 是 而不是 由 nextInt()
、nextDouble()
、next()
或 nextFoo()
方法使用。
因此,无论何时您在任何这些方法之后调用 nextLine()
,它都会消耗 newline,并且实际上跳过了该语句。
修复很简单,不要在 nextLine()
之前使用 nextFoo()
方法。尝试:-
i2 = Integer.parseInt(scan.nextLine());
d2 = Double.parseDouble(scan.nextLine());
s2 = scan.nextLine();
否则,您可以使用 new-line by
i2 = scan.nextInt();
d2 = scan.nextDouble();
scan.nextLine(); //---> Add this before the nextLine() call
s2 = scan.nextLine();
Order#3 工作正常,因为 nextLine()
是第一个语句,因此,有 no 剩余 个字符供消耗。
相关:Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods