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

标签 java set java.util.scanner

我有这个代码:

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(); 造成的吗?

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

  • 删除该行:

    sc.useDelimiter(System.getProperty("line.separator"));
    
  • 替换行:

    String element = sc.next();
    

    与:

    String element = sc.next() + " " + scan.next()j
    

请澄清一下吗?

最佳答案

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

    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 值,换行符就会被留下并在循环中被读取并产生错误的结果。您可以使用 nextLine() 调用读取该换行符并忽略它。然后根据要求使用 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

关于java - Java中使用Scanner读取整行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32994950/

相关文章:

C++ std::set 更新很乏味:我无法就地更改元素

java - 如果没有输入任何内容,如何检查 Scanner.hasNext(System.in) 是否超时?

java - 尝试使用扫描仪时出现"Cannot be resolved to a type"

java - 如何在 java 中关闭扫描仪?

java - 配置单元顶点失败 : killed/failed due to:ROOT_INPUT_INIT_FAILURE Caused by: java. lang.NullPointerException

Java 通用 : Operator "*" cannot be applied to T, T 。我很难理解通用的

java.sql.SQLException : Row 1 was truncated; it contained more data than there were input columns 异常

java - 从 Eclipse 插件使用 Jython

c++ - 从集合中删除元素的问题

c++ - C++中如何匹配两个数组的内容