int n = sc.nextInt();
char[][] original = new char[n][n];
char [][] result = new char[n][n];
String line;
for (int i = 0; i < n; i++) {
line = sc.nextLine();
System.out.println(line);
for (int u = 0; u < n; u++) {
original[i][u] = line.charAt(u);
}
}
for (int i = 0; i < n; i++) {
line = sc.nextLine();
for (int u = 0; u < n; u++) {
result[i][u] = line.charAt(u);
}
}
I have a file that looks like this:
2
ha
ah
lo
ol
I have an integer N on firs line, and then two N*N matrixes of characters.
I am trying to read them to two arrays of arrays of chars, but I get this error:
Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at transform.main(transform.java:25)
Line 25 is this:
original[i][u] = line.charAt(u);
I just don’t get it, I think I’m doing everything just fine. Any ideas? Thank you!
I suppose your
scis a scanner instance? The methodnextInt()does read the next number from your file but does not process the following newline. Thus, your first call tonextLine()will return just an empty string (i.e. all characters until the newline which was not processed yet). You will see that youprintln(...)call does print an empty line. You may insert a call tonewLine()before your loop to fix this behavior.