输入我必须处理:
2
2 3
3 3
我的代码:
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[][] array = new int[size][2];
Scanner scanner2 = new Scanner(System.in);
for (int i=0; i<size; i++) {
for (int j=0; j<2; j++) {
array[i][j] = scanner2.nextInt();
}
}
2
是输入包含的对数。我想把这些对放在2D数组中,但我需要首先得到2
来声明数组的大小。上面的代码在NetBeans中运行良好,我提供的输入如下:
number
enter
pair
enter
...
但所有数字都以我上面发布的格式汇集在一起。
任何帮助?
答案 0 :(得分:1)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter an integer");
int size = scanner.nextInt();
int[][] array = new int[size][2];
for (int i = 0; i < size; i++) {
String myInt = scanner.next();
String[] myInts = myInt.split(" ");
for (int j = 0; j < 2; j++) {
array[i][j] = Integer.parseInt(myInts[j]);
}
}
// print contents
for (int i = 0; i < size; i++) {
for (int j = 0; j < 2; j++) {
System.out.println("[" + i + "]" + "[" + j + "] = " +array[i][j]);
}
}
}