Java中Scanner的nextLine问题

3
只有一个问题:为什么必须两次输入answer = in.nextLine();呢?如果只有一行,则程序无法按预期工作。没有第二行,程序不会要求您输入字符串。
public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String answer = "Yes";

        while (answer.equals("Yes")) {
            System.out.println("Enter name and rating:");
            String name = in.nextLine();
            int rating = 0;

            if (in.hasNextInt()) {
                rating = in.nextInt();
            } else {
                System.out.println("Error. Exit.");
                return;
            }

            System.out.println("Name: " + name);
            System.out.println("Rating: " + rating);
            ECTS ects = new ECTS();
            rating = ects.checkRating(rating);
            System.out.println("Enter \"Yes\" to continue: ");
            answer = in.nextLine();
            answer = in.nextLine();
        }

        System.out.println("Bye!");
        in.close();
    }
}

1
你不应该需要写两次。o.o - EpicPandaForce
3
nextInt()会在后面留下一个换行符。你的第一个nextLine()会把它读取掉。第二个nextLine()将读取你的“Yes”数据。 - TheLostMind
@Zhuinden - 他正在使用 nextInt(),他将不得不。 - TheLostMind
@TheLostMind 哦,这就像是在 C 中使用 scanf 时遇到的问题。我总是使用 BufferedReader,所以没有遇到过这样的情况。感谢您的回答! - EpicPandaForce
1
@Zhuinden - 扫描器通常用于解析FileReader/BufferedReader通常用于读取 - TheLostMind
2个回答

4

Scanner-对象有一个内部缓存。

  1. 您开始扫描 nextInt()
  2. 您按下键 1
  3. 您按下键 2
  4. 您按下 return

现在,内部缓存有 3 个字符,扫描器看到第三个字符(return)不是数字,因此 nextInt() 只会返回第 1 个和第 2 个字符的整数 (1,2=12)。

  1. nextInt() 返回 12。

不幸的是,return 仍然是 Scanner 的缓存的一部分。

  1. 您调用 nextLine(),但该方法会扫描其缓存以查找先前从 nextInt() 调用返回时保留在缓存中的 newline-标记。

  2. nextLine() 返回一个长度为 0 的字符串。

  3. 下一个 nextLine() 没有缓存!它将等待缓存被填充下一个 newline-标记。

reset()

有一种更优雅的方法来清除缓存,而不是使用 nextLine()

in.reset();

2

因为你使用了nextInt()这个方法,它只会获取下一个整数,但不会消耗掉 \n 字符,所以当你再次使用nextLine()时,它会先消耗完该行的剩余部分,然后才会移动到下一行。


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