have the text file containing a 2d array with a fixed row and column [6][3]
让文本文件包含一个带有固定行和列的二维数组[6] [3]
a 5 7
b 9 7
c 1 0
d 0 5
e 8 7
f 0 4
i need to put the data into array playerOne[][]
我需要将数据放入数组playerOne [] []
This is my code
这是我的代码
try {
Scanner sc = new Scanner(new File("test.txt"));
while (sc.hasNextLine()) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 3; j++) {
String line = sc.next().trim();
if (line.length() > 0) {
playerOne[i][j] = line;
System.out.println(i+ " " +j+ " "+ line);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(Arrays.toString(playerOne));
}
i get an NoSuchElementException error, and it cannot print the array
我收到NoSuchElementException错误,它无法打印数组
1 个解决方案
#1
1
instead of using nextLine
use .next
directly .next will get the next value regardless to the next value line
而不是使用nextLine直接使用.next .next将获得下一个值,而不管下一个值行
try {
Scanner sc = new Scanner(new File("test.txt"));
while (sc.hasNext()) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 3; j++) {
String nextValue= sc.next().trim();
playerOne[i][j] = nextValue;
System.out.println(i+ " " +j+ " "+ nextValue);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(Arrays.toString(playerOne));
}
#1
1
instead of using nextLine
use .next
directly .next will get the next value regardless to the next value line
而不是使用nextLine直接使用.next .next将获得下一个值,而不管下一个值行
try {
Scanner sc = new Scanner(new File("test.txt"));
while (sc.hasNext()) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 3; j++) {
String nextValue= sc.next().trim();
playerOne[i][j] = nextValue;
System.out.println(i+ " " +j+ " "+ nextValue);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(Arrays.toString(playerOne));
}