我试图从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]);
}
}
}
答案 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]);
}
}
}