have the text file containing a 2d array with a fixed row and column [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[][]
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
instead of using nextLine
use .next
directly .next will get the next value regardless to the next value line
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));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.