简体   繁体   English

为什么Java不会在这里打印最后一个字?

[英]Why won't Java print last word here?

Why does this print the entire string "1fish2fish"... 为什么打印整个字符串“1fish2fish”......

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    String input = "1,fish,2,fish";
    Scanner sc = new Scanner(input);
    sc.useDelimiter(",");
    System.out.print(sc.nextInt());
    System.out.println(sc.next());
    System.out.print(sc.nextInt());
    System.out.println(sc.next());
  }
}

But this only prints "1fish2" even though I enter "1,fish,2,fish"? 但即使我输入“1,鱼,2,鱼”,这只打印“1fish2”?

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    System.out.println("Enter your string: ");
    Scanner sc = new Scanner(System.in);
    sc.useDelimiter(",");
    System.out.print(sc.nextInt());
    System.out.println(sc.next());
    System.out.print(sc.nextInt());
    System.out.println(sc.next());
  }
}

In the first case, the scanner doesn't need the last delimiter, as it knows that there are no more characters. 在第一种情况下,扫描仪不需要最后的分隔符,因为它知道没有更多的字符。 So, it knows that the last token is 'fish' and there are no more characters to process. 因此,它知道最后一个标记是'fish',并且不再需要处理任何字符。

In the case of a System.in scan, the fourth token is considered as completed only when the fourth ',' is entered in the system input. 在System.in扫描的情况下,仅当在系统输入中输入第四个“,”时,才认为第四个标记已完成。

Note that white spaces are considered as delimiters by default. 请注意,默认情况下,空格被视为分隔符。 But, once you specify an alternate delimiter using useDelimiter, then white space characters don't demarcate tokens any more. 但是,一旦使用useDelimiter指定备用分隔符,则空格字符不再标记标记。

In fact, your first trial can be modified to prove that white space characters are not delimiters any more... 事实上,您的第一次试用可以修改,以证明空白字符不再是分隔符...

  public static void main(String[] args) {
    String input = "1,fish,2,fish\n\n\n";
    Scanner sc = new Scanner(input);
    sc.useDelimiter(",");
    System.out.print(sc.nextInt());
    System.out.println(sc.next());
    System.out.print(sc.nextInt());
    System.out.println(sc.next());

    System.out.println("Done");
    sc.close();

  }

The new line characters will be treated as part of the fourth token. 新行字符将被视为第四个标记的一部分。

I checked the first snippet; 我检查了第一个片段; it is correctly printing - 它正确打印 -

  1fish
  2fish

Link - http://code.geeksforgeeks.org/jK1Mlu 链接 - http://code.geeksforgeeks.org/jK1Mlu

Please let us know if your expectation is different. 如果您的期望不同,请告诉我们。

Scanner waits for you to enter another ',' so when you will enter ',' then after that it will immediately prints fish after 1fish2 . 扫描仪等待你输入另一个','所以当你输入','然后它会在1fish2之后立即打印鱼。

so Pass 1,fish,2,fish, instead of 1,fish,2,fish 所以通过1,fish,2,fish,而不是1,fish,2,fish

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

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