为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

蛊毒传说 2019-05-20 15:54:17
我正在使用这些Scanner方法nextInt()并nextLine()阅读输入。它看起来像这样:System.out.println("Enter numerical value");    int option;option = input.nextInt(); // Read numerical value from inputSystem.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 value3   // This is my inputEnter 1st string    // The program is supposed to stop here and wait for my input, but is skippedEnter 2nd string    // ...and this line is executed and waits for my input我测试了我的应用程序,看起来问题在于使用input.nextInt()。如果我删除它,然后这两个string1 = input.nextLine()和string2 = input.nextLine()执行,我希望他们能。
查看完整描述

4 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

那是因为该Scanner.nextInt方法没有读取通过点击“Enter”创建的输入中的换行符,因此Scanner.nextLine在读取该换行符后返回调用。

当您使用Scanner.nextLineafter Scanner.next()或任何Scanner.nextFoo方法(nextLine自身除外)时,您将遇到类似的行为。

解决方法:

  • 要么把一个Scanner.nextLine电话后,每Scanner.nextIntScanner.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();


查看完整回答
反对 回复 2019-05-20
?
HUWWW

TA贡献1874条经验 获得超12个赞


问题在于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();


查看完整回答
反对 回复 2019-05-20
?
慕哥9229398

TA贡献1877条经验 获得超6个赞

这是因为当你输入一个数字然后按Enterinput.nextInt()只消耗数字,而不是“行尾”。当input.nextLine()执行时,它会消耗来自第一输入缓冲器中的“行结束”静止。

相反,请input.nextLine()立即使用input.nextInt()


查看完整回答
反对 回复 2019-05-20
  • 4 回答
  • 0 关注
  • 895 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信