使用next()或nextFoo()后,Scanner跳过了nextLine()吗?

943

我正在使用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()被执行了,因此我的输出看起来像这样:

问题是在输入数值后,第一个 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()就会像我希望的那样执行。


13
你也可以像我一样使用 BufferedReader :) 我不在乎它是否过时,它一直都为我工作并且将来也会。此外,掌握 BufferedReader 在其他地方也很有用。我只是不喜欢 Scanner。 - Cruncher
25个回答

2
为了解决这个问题,只需使用scan.nextLine(),其中scan是Scanner对象的实例。例如,我正在使用一个简单的HackerRank问题进行说明。
package com.company;
import java.util.Scanner;

public class hackerrank {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int i = scan.nextInt();
    double d = scan.nextDouble();
    scan.nextLine(); // This line shall stop the skipping the nextLine() 
    String s = scan.nextLine();
    scan.close();



    // Write your code here.

    System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);
}

}


1
 Scanner scan = new Scanner(System.in);
    int i = scan.nextInt();
    scan.nextLine();//to Ignore the rest of the line after  (integer input)nextInt()
    double d=scan.nextDouble();
    scan.nextLine();
    String s=scan.nextLine();
    scan.close();
    System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);

1
问题出在input.nextInt()方法上-它只读取int值。所以当你继续使用input.nextLine()读取时,你会收到"\n"回车键。因此,为了跳过这一步,你需要添加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();

0
为什么不为每次读取使用一个新的Scanner?像下面这样。采用这种方法,您将不会遇到问题。
int i = new Scanner(System.in).nextInt();

3
然后你需要关闭Scanner以防止内存泄漏。这会浪费时间吗? - TheCoffeeCup
1
如果Scanner被包装在一个方法中,GC难道不会处理它吗?例如:String getInput() {return new Scanner(System.in).nextLine()}; - Tobias Johansson
1
这是绝对不正确的。nextInt() 不会消耗换行符,无论它是在一个“新”的 Scanner 中还是在已经使用过的 Scanner 中。 - Dawood ibn Kareem

0
使用 BufferedReader 类输入字符串,这不会创建问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接