简体   繁体   English

使用扫描仪读取Java中String的整行

[英]Using Scanner to read entire line of String in Java

I have this code: 我有以下代码:

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());
    }
}

Input: 输入:

5
john tom
john mary
john tom
mary anna
mary anna

My Output (stdout) 我的输出(标准输出)

1
2
3
3
4

Expected Output 预期产量

1
2
2
3
3

Why it differs? 为什么不同? Is it due to Scanner$nextLine(); 是否由于Scanner$nextLine(); ?

However, I get correct output if I perform following changes: 但是,如果执行以下更改,则会得到正确的输出:

  • Remove the line: 删除行:

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

     String element = sc.next(); 

    with: 与:

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

Please clarify the same? 请说明相同吗?

Here is the code which is giving you the wrong output: 这是给您错误输出的代码:

    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());
      }

Output: 输出:
1 1个
2 2
3 3
3 3
4 4


The issue is once you read the int value, new line character is left behind and gets read in the loop and produces wrong result. 问题是一旦您读取了int值, new line character就会被留下并在循环中被读取并产生错误的结果。 You can read that new line character using a nextLine() call and ignore it. 您可以使用nextLine()读取该new line character然后忽略它。 Then use the nextLine() method as per the requirement. 然后根据需要使用nextLine()方法。

Here is the code producing the correct result. 这是产生正确结果的代码。

    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());
      }

Output: 输出:
1 1个
2 2
2 2
3 3
3 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM