The following code should read 5 strings from a .dat file and then print each individual character from each of the strings.
File file = new File("tictactoe.dat");
Scanner scan = new Scanner(file);
String str = "";
int x;
for ( x = 0; x < numGames; x++) {
str = scan.nextLine();
for (int i = 0; i < str.length(); i++) {
out.println(str.charAt(i));
}
}
But the program throws a StringIndexOutOfBoundsException. There’s nothing wrong with the Scanner, as tests have shown that it picks up each line in my file fine. But when attempting to get and then print a certain character in each string, the program crashes.
Strangely, outside of the loop charAt() works without error.
Why does calling the method within the loop cause the progam to crash?
UPDATE: I made some ridiculous mistake copying the code I was using. Please see updated code above. Also, the program “crashes” due to a StringIndexOutOfBoundsException, which I am not catching.
Your loop isn’t doing what you want it to do. You say:
But what it’s actually doing is getting line 1, and printing only the first character from that line, then getting the second line and printing the second character, third line and third character, and so on. If you’re printing each character on a separate line, you need to have a second loop inside your first one that iterates through the characters in the string in order to print all their individual characters.
Or even better, if you use a for-each loop: