我正在使用这些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)
Run Code Online (Sandbox Code Playgroud)
问题是输入数值后,第一个input.nextLine()被跳过而第二个input.nextLine()被执行,所以我的输出如下所示:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and …Run Code Online (Sandbox Code Playgroud) 我经常遇到这个问题.当我多次使用扫描仪时,它不会从用户那里获得输入.
Scanner scan = new Scanner(System.in);
System.out.println("1---");
int try1 = scan.nextInt();
System.out.println("2---");
int try2 = scan.nextInt();
System.out.println("3---");
String try3 = scan.nextLine();
System.out.println("4---");
String try4 = scan.nextLine();
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,结果:
1 ---
12
2 ---
321
3 ---
4 ---
AA
如您所见,它跳过了第3个输入.为什么会这样?我使用新的扫描仪解决了这个问题,有时我有5-6种不同的扫描仪,看起来很复杂.另一个问题是:存在错误"资源泄漏:扫描永远不会关闭".我真的很困惑.