在使用next()或nextFoo()之后,Scanner正在跳过nextLine()?


我正在使用这些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()执行,我希望他们能。


蛊毒传说
浏览 896回答 4
4回答

慕村225694

那是因为该Scanner.nextInt方法没有读取通过点击“Enter”创建的输入中的换行符,因此Scanner.nextLine在读取该换行符后返回调用。当您使用Scanner.nextLineafter Scanner.next()或任何Scanner.nextFoo方法(nextLine自身除外)时,您将遇到类似的行为。解决方法:要么把一个Scanner.nextLine电话后,每Scanner.nextInt或Scanner.nextFoo消耗该行包括休息换行符int option = input.nextInt();input.nextLine();  // Consume newline left-overString str1 = input.nextLine();或者,更好的是,通过读取输入Scanner.nextLine并将输入转换为您需要的正确格式。例如,您可以使用Integer.parseInt(String)方法转换为整数。int option = 0;try {     option = Integer.parseInt(input.nextLine());} catch (NumberFormatException e) {     e.printStackTrace();}String str1 = input.nextLine();

HUWWW

问题在于input.nextInt()方法 - 它只读取int值。因此,当您继续使用input.nextLine()读取时,您会收到“\ n”Enter键。所以要跳过这个,你必须添加input.nextLine()。希望现在应该清楚这一点。试试这样:System.out.print("Insert a number: ");int number = input.nextInt();input.nextLine(); // This line you have to add (It consumes the \n character)System.out.print("Text1: ");String text1 = input.nextLine();System.out.print("Text2: ");String text2 = input.nextLine();

慕哥9229398

这是因为当你输入一个数字然后按Enter,input.nextInt()只消耗数字,而不是“行尾”。当input.nextLine()执行时,它会消耗来自第一输入缓冲器中的“行结束”静止。相反,请input.nextLine()立即使用input.nextInt()
打开App,查看更多内容
随时随地看视频慕课网APP