为什么Java在这里无法打印最后一个单词?

3
为什么会输出整个字符串“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());
  }
}

但即使我输入“1,fish,2,fish”,它只会打印出“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());
  }
}

http://ideone.com/3nVHEP - Rahul Tripathi
3个回答

4
在第一种情况下,扫描仪不需要最后一个定界符,因为它知道没有更多的字符了。因此,它知道最后一个标记是'fish',并且没有更多的字符需要处理。
在System.in扫描的情况下,只有在第四个','输入到系统输入中时,第四个标记才被认为是完成的。
请注意,默认情况下,空格被视为定界符。但是,一旦您使用useDelimiter指定备用定界符,则空格字符就不再划分标记。
事实上,您的第一次尝试可以修改以证明空格字符不再是定界符...
  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();

  }

新行字符将被视为第四个标记的一部分。

1

是的,第一段代码片段按预期输出了。第二个是我不理解的有问题的那个。 - Travis Smith

0

Scanner 等待您输入另一个“,”,因此当您输入“,”后,它将立即在 1fish2 之后打印 fish。

因此,请传递 1,fish,2,fish, 而不是 1,fish,2,fish


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