【问题标题】:Reading multiple lines from console in java在java中从控制台读取多行
【发布时间】:2016-11-22 23:43:27
【问题描述】:

我需要从控制台获取多行输入,这些输入将是我的班级问题的整数。到目前为止,我一直在使用扫描仪,但我没有解决方案。输入由 n 行组成。输入以一个整数开头,然后是一系列整数,这会重复很多次。当用户输入 0 时,即停止输入。

例如

输入:

3
3 2 1
4
4 2 1 3
0

那么我如何阅读这一系列的行,并可能使用扫描仪对象将每一行存储为数组的一个元素?到目前为止,我已经尝试过:

 Scanner scan = new Scanner(System.in);
    //while(scan.nextInt() != 0)
    int counter = 0;
    String[] input = new String[10];

    while(scan.nextInt() != 0)
    {
        input[counter] = scan.nextLine();
        counter++;
    }
    System.out.println(Arrays.toString(input));

【问题讨论】:

  • 你遇到了这个skipping issue
  • 您需要 2 个循环:一个读取数量的外部循环和一个读取那么多整数的内部循环。在两个循环结束时,您需要 readLine()

标签: java java.util.scanner


【解决方案1】:

您需要 2 个循环:一个读取数量的外部循环和一个读取那么多整数的内部循环。在两个循环结束时,您需要readLine()

Scanner scan = new Scanner(System.in);

for (int counter = scan.nextInt(); counter > 0; counter = scan.nextInt()) {
    scan.readLine(); // clears the newline from the input buffer after reading "counter"
    int[] input = IntStream.generate(scan::nextInt).limit(counter).toArray();
    scan.readLine(); // clears the newline from the input buffer after reading the ints
    System.out.println(Arrays.toString(input)); // do what you want with the array
}

为了优雅(恕我直言),内部循环是用流实现的。

【讨论】:

    【解决方案2】:

    您可以使用 scan.nextLine() 获取每一行,然后通过将其拆分为空格字符来解析该行中的整数。

    【讨论】:

      【解决方案3】:

      正如mWhitley所说,只需使用String#split在空格字符上分割输入行

      这会将每行的整数保存到一个列表中并打印出来

      Scanner scan = new Scanner(System.in);
      ArrayList integers = new ArrayList();
      
      while (!scan.nextLine().equals("0")) {
          for (String n : scan.nextLine().split(" ")) {
              integers.add(Integer.valueOf(n));
          }
      }
      
      System.out.println((Arrays.toString(integers.toArray())));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-04
        • 2014-12-15
        • 2019-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-05
        相关资源
        最近更新 更多