Scanner 在使用 next() 或 nextFoo() 后是否跳过 nextLine()?
2022-08-31 04:01:33
我正在使用这些方法和读取输入。Scanner
nextInt()
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()
string2 = input.nextLine()