从Stdin读取并分割多行

时间:2016-07-25 10:49:45

标签: java arrays split java.util.scanner

我试图从stdin中读取两行输入,并将第一行的项目复制到一个数组中,将第二行的项目复制到另一个数组中。每行中的项目之间都有空格,我用它来区分项目。输入的一个例子是:

1 2 3
4 5 

目前12345存储在一个数组中,但我希望结果如下:

arr1 = [1, 2, 3];
arr2 = [4, 5];

我该怎么做?

import java.util.*;

public class Tester {   

  public static void main (String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter lines:");  

    while(input.hasNext()) {

      String s = input.nextLine();
      String[] strArray = s.split(" ");

      int[] intArray = new int[strArray.length];

      for(int i = 0; i < strArray.length; i++) {
        intArray[i] = Integer.parseInt(strArray[i]);
        System.out.print(intArray[i]);
      }
    }
} 

1 个答案:

答案 0 :(得分:0)

You should extract the parsing of a single line to a separate method:

private static int[] parseInts(String s) {
  String[] strArray = s.split(" ");

  int[] intArray = new int[strArray.length];

  for(int i = 0; i < strArray.length; i++) {
    intArray[i] = Integer.parseInt(strArray[i]);
  }
  return intArray;
}

After that, the code in main looks simpler:

public static void main (String[] args) {

  Scanner input = new Scanner(System.in);
  System.out.println("Enter lines:");

  int[] line1Numbers = parseInts(input.nextLine());
  int[] line2Numbers = parseInts(input.nextLine());

  // For the remaining lines:
  while(input.hasNext()) {
    String line = input.nextLine();
    int[] numbers = parseInts(line);

    for(int i = 0; i < strArray.length; i++) {
      System.out.print(intArray[i]);
    }
  }
}