使用 Scanner 读取 Java 中的整行字符串

Using Scanner to read entire line of String in Java

我有这个代码:

Set<String> uniquePairs = new HashSet<String>();
Scanner sc = new Scanner(System.in);

int t = sc.nextInt();
sc.useDelimiter(System.getProperty("line.separator"));

for(int i=0; i<t ;++i) {
    if(sc.hasNext()) {
        String element = sc.next();
        uniquePairs.add(element);
        System.out.println(uniquePairs.size());
    }
}

输入:

5
john tom
john mary
john tom
mary anna
mary anna

我的输出(标准输出)

1
2
3
3
4

预期输出

1
2
2
3
3

为什么不同?是因为Scanner$nextLine();吗?

但是,如果我执行以下更改,我会得到正确的输出:

请澄清一下?

这是给你错误输出的代码:

    Set<String> uniquePairs = new HashSet<String>();
    Scanner sc = new Scanner(System.in);
    int t = sc.nextInt();
    sc.useDelimiter(System.getProperty("line.separator"));
    for(int i=0; i<t ;++i) {
      if(sc.hasNextLine()) {
        String element = sc.nextLine();
        uniquePairs.add(element);
        System.out.println(uniquePairs.size());
      }

输出:
1
2
3
3
4


问题是一旦您读取了 int 值,new line character 就会被留在后面并在循环中读取并产生错误的结果。您可以使用 nextLine() 调用读取 new line character 并忽略它。然后根据要求使用 nextLine() 方法。

这是产生正确结果的代码。

    Set<String> uniquePairs = new HashSet<String>();
    Scanner sc = new Scanner(System.in);
    int t = sc.nextInt();
    sc.nextLine();    // Ignore the next line char.

    for(int i=0; i<t ;++i) {
      if(sc.hasNextLine()) {
        String element = sc.nextLine();
        uniquePairs.add(element);
        System.out.println(uniquePairs.size());
      }

输出:
1
2
2
3
3