【问题标题】:Why won't Java print last word here?为什么 Java 不会在这里打印最后一个字?
【发布时间】:2016-06-20 07:00:17
【问题描述】:

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

【问题讨论】:

标签: java java.util.scanner system.in


【解决方案1】:

在第一种情况下,扫描仪不需要最后一个分隔符,因为它知道没有更多的字符。因此,它知道最后一个标记是“鱼”,并且没有要处理的字符了。

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

  }

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

【讨论】:

    【解决方案2】:

    我检查了第一个sn-p;它正在正确打印 -

      1fish
      2fish
    

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

    如果您的期望有所不同,请告诉我们。

    【讨论】:

    • 是的,第一个 sn-p 正在按预期打印。第二个是我理解有问题的那个。
    【解决方案3】:

    扫描仪会等待您输入另一个 ',',所以当您输入 ',' 之后,它会立即在 1fish2 之后打印 fish。

    所以通过1,fish,2,fish, 而不是1,fish,2,fish

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 2013-09-28
      相关资源
      最近更新 更多