扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine() 吗? [英] Scanner is skipping nextLine() after using next() or nextFoo()?

查看:23
本文介绍了扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine() 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Scanner 方法 nextInt()nextLine() 来读取输入.

I am using the Scanner methods nextInt() and nextLine() for reading input.

看起来像这样:

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(),这样我的输出看起来像这样:

The problem is that after entering the numerical value, the first input.nextLine() is skipped and the second input.nextLine() is executed, so that my output looks like this:

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() 都会按照我想要的方式执行.

I tested my application and it looks like the problem lies in using input.nextInt(). If I delete it, then both string1 = input.nextLine() and string2 = input.nextLine() are executed as I want them to be.

推荐答案

那是因为 Scanner.nextInt 方法不会读取通过点击Enter," 以及对 <的调用code>Scanner.nextLine 读取该换行符后返回.

Scanner.next() 或任何 Scanner.nextFoo 方法(除了 nextLine 本身).

You will encounter the similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself).

解决方法:

  • 在每个 Scanner.nextIntScanner.nextFoo 之后调用 Scanner.nextLine 调用以消耗该行的其余部分,包括换行

  • Either put a Scanner.nextLine call after each Scanner.nextInt or Scanner.nextFoo to consume rest of that line including newline

int option = input.nextInt();
input.nextLine();  // Consume newline left-over
String str1 = input.nextLine();

  • 或者,更好的是,通过 Scanner.nextLine 读取输入并将您的输入转换为您需要的正确格式.例如,您可以使用 Integer.parseInt(String) 方法.

  • Or, even better, read the input through Scanner.nextLine and convert your input to the proper format you need. For example, you may convert to an integer using Integer.parseInt(String) method.

    int option = 0;
    try {
        option = Integer.parseInt(input.nextLine());
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    String str1 = input.nextLine();
    

  • 这篇关于扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆