我正在使用Scanner
方法nextInt()
and nextLine()
用于读取输入。
它看起来像这样:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
问题是,输入数值后,第一个input.nextLine()
被跳过,第二个input.nextLine()
被执行,所以我的输出如下所示:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string // ...and this line is executed and waits for my input
我测试了我的应用程序,看起来问题在于使用input.nextInt()
。如果我删除它,那么两者string1 = input.nextLine()
and string2 = input.nextLine()
按照我想要的方式执行。
那是因为Scanner.nextInt http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29方法不读取newline通过按“Enter”创建输入中的字符,因此调用Scanner.nextLine http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine%28%29读完后返回newline.
当你使用时你会遇到类似的行为Scanner.nextLine
after Scanner.next() http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next%28%29 or any Scanner.nextFoo
方法(除了nextLine
本身)。
解决方法:
-
要么放一个Scanner.nextLine
每次之后打电话Scanner.nextInt
or Scanner.nextFoo
消耗该行的其余部分,包括newline
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
-
或者,更好的是,通过读取输入Scanner.nextLine
并将您的输入转换为您需要的正确格式。例如,您可以使用转换为整数Integer.parseInt(String) http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String) method.
int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)