I'm really confused. I'm trying to read a matrices from a text file, and I keep getting errors. The error always comes out in the last line of that for loop with the charAt(z) part.
The error says: java.lang.StringIndexOutOfBoundsException: String index out of range: 0. I want to read each individual character in each row.
Notes: I've already read the column and rows variables from the text file, and read in the variable input from the user earlier in the code and that part works fine. It's this for loop I'm having problems with. This is obviously not the full code, just the troublesome section.
I am not sure probably this is happening in your case.
You must be getting an empty string in garbage. That is the reason of Exception. So if string is empty it will not find any value at index 0. Like in above program for first value in names array you will get
if you remove that first element from array you will get
But for the last element you will not get any exception becuase the number of columns are equal to the size of string.
You can remove this exception using following code;
Well the problem is, I think, that the text file is like this:
I need to get past that empty line with my scanner in order to read the matrix. Using .isEmpty in the way you wrote seems like it would make my program not error when compiling, but I it won't go into the for loop unless I get past that emply line, and calling .nextLine() an extra time doesn't seem to be getting past that empty line like I thought it would.
How did you sort out your problem? Please show us. I would have put in a test like while ((input = myScanner.nextLine()).length() == 0); Note the ; at the end of the "while", a feature you must mark with a comment like /* empty */; this means do nothing as long as you have a zero-length string read from the file. The length() and while and == won't cause a performance overhead. Once you have a non-zero-length string, it is assigned to "input" ready for use.