获取输入直到出现空行,然后将该行转换为String 数组,使用空格作为分隔符。然后将每个元素解析为int,并放到一个临时的ArrayList<Integer>。 ArrayList<Integer> 中的已解析整数将放在主 ArrayList 中。
ArrayList 的结构将是 ArrayList 的 ArrayList<Integer>
import java.util.*;
public class MultiLine {
public static void main (String[] args) {
Scanner sc = new Scanner( System.in );
System.out.println("Input:");
// main ArrayList
ArrayList < ArrayList<Integer> > lst = new ArrayList < ArrayList<Integer> >();
// input process
while ( sc.hasNextLine() ) {
String line = sc.nextLine();
// stops input if line is empty
if ( line.equals("") )
break;
// splits line to String array, using space as delimiter
String[] splittedLine = line.split(" ");
// temporary ArrayList that will parse each number from lines seperated by space
ArrayList <Integer> temp = new ArrayList <Integer>();
// parses each String of splittedLine to int, adds it to temp ArrayList
for( String num : splittedLine ) {
try {
temp.add( Integer.parseInt(num) );
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
// adds temp ArrayList to lst
lst.add( temp );
}
System.out.println( lst );
}
}
样本运行
Input:
1 2 3 4 5
2 4 6 8 10
12 14
895 623 1245 1
[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [12, 14], [895, 623, 1245, 1]]