So I get that String index out of range means that I'm exceeding the range of a collection, but I'm not quite sure how I'm doing that with my code.
This code is supposed to read from a text file which contains 3 ints( the first two being what are relevant to this as the number of rows and number of columns respectively) and then a series of characters. So first it reads and saves the first three numbers, then converts the rest of the file to String. It then follows this up by setting up an array of chars with the dimensions of the text file and then filling in those values with the characters of the text file character by character.
However, when I try to print out the code, I encounter the string index out of range error and cannot find the problem.
This is the code:
import java.util.*;
import java.io.*;
public class SnakeBox {
// instance variables
private char[][] box;
private int snakeCount;
private int startRow, startCol;
private int endRow, endCol;
private int rows, cols, snakes;
Scanner keyboard = new Scanner(System.in);
/** Create and initialize a SnakeBox by reading a file.
@param filename the external name of a plain text file
*/
public SnakeBox(String fileName) throws IOException{
Scanner infile = new Scanner(new FileReader(fileName));
int count = 0;
String s = "";
rows = infile.nextInt();
cols = infile.nextInt();
snakes = infile.nextInt();
infile.nextLine();
box = new char[rows][cols];
while (infile.hasNext()) {
s += infile.next();
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
count++;
char c = s.charAt(count);
box [i][j] = c;
}
}
}
The text file is :
16 21 4
+++++++++++++++++++++
+ +
+ SSSSS +
+ S S +
+ S SS +
+ S S +
+ S S SS +
+ SS S +
+ S +
+ S SSSSSS +
+ S S +
+ S S +
+ S SSS S +
+ S S +
+ SSSSS +
+++++++++++++++++++++
Thank you.