I'm trying to input data from a file that's in the form of
1000
16 11
221 25
234 112
348 102
451 456
183 218
78 338
365 29
114 393
441 369
531 460
...
I'm having trouble because I keep getting IndexOutOfBounds exceptions or NoSuchElement exceptions. How do I put the data into an array so that I can easily sort it later?
public class shortestRoute { public static void printGrid(int[][] adjMat) { for(int i = 0; i < 1000; i++) { for(int j = 0; j < 2; j++) { System.out.printf("%5d", adjMat[i][j]); } System.out.println(); } } public static void main(String[] args) throws IOException { File file = new File("rtest1-2.dat"); Scanner scanner = new Scanner(file); scanner.useDelimiter("\\\\s+"); int N = scanner.nextInt(); int[][] adjMat = new int[N][2]; for(int i=0; i < N; i++) for (int j=0; j < 2; j++) adjMat[i][j] = scanner.nextInt(); printGrid(adjMat); } }
You're iterating to much. You have 1000 lines with 2 Integer
but you are iterating over 1000x1000 Integer
. Just switch the inner for loop to a max of 2:
for(int i=0; i < N; i++){
for (int j=0; j < 2; j++) {
adjMat[i][j] = scanner.nextInt();
}
}
and you should also lower the allocation of your array:
int[][] adjMat = new int[N][2];
int N = scanner.nextInt();
This will pick up N as 1000. But in the given as example you got only 22 integers and the NoSuchElement errors comes right after 22nd element.
if you provide enough input, then you can get rid of this error. Cheers!
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.