I've written a program that displays tokens dropped into a board depending on the user's selection of which column to drop it in. I'm getting a runtime error
java.lang.StringIndexOutOfBoundsExcepti… String index out of range: 42
at java.lang.String.substring(Unknown Source)
at A1Program.extractRow(A1Program.java:83)
at A1Program.start(A1Program.java:19)
at A1Application.main(A1Application.java:11…
at sun.reflect.NativeMethodAccessorImpl.inv… Method)
at sun.reflect.NativeMethodAccessorImpl.inv… Source)
at sun.reflect.DelegatingMethodAccessorImpl… Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacC…
when I run the program, and I'm a bit lost as to where I might have gone wrong.
My code is:
public class A1Program {
public void start() {
String inputString = "XOXOXOO X XXO X OXO ";
boolean gameOver = false;
String tokens = inputString;
while (!gameOver) {
int column = columnResult();
tokens = enterToken("X", tokens, column);
System.out.println(tokens);
displayBoard(extractRow(5, tokens));
displayBoard(extractRow(4, tokens));
displayBoard(extractRow(3, tokens));
displayBoard(extractRow(2, tokens));
displayBoard(extractRow(1, tokens));
displayBoard(extractRow(0, tokens));
System.out.println("---------------");
}
}
private int columnResult(){
System.out.println("Enter column for X:");
String keyInput = Keyboard.readInput();
int column1 = Integer.parseInt(keyInput);
return column1;
}
private String enterToken(String tokenSymbol, String inputString, int column){
String columnEdit = inputString.substring(column*6-6,column*…
String columnEdit1 = columnEdit.trim();
String columnEdit2 = columnEdit1+tokenSymbol+" ";
String columnEdit3 = columnEdit2.substring(0,6);
String start = inputString.substring(0,column*6-6);
String end = inputString.substring(column*6);
System.out.println(start);
return start+tokenSymbol+end;
}
private String extractRow(int row, String tokens) {
String rowString1 = tokens.substring(row, row + 1);
String rowString2 = tokens.substring(row + 6, row + 7);
String rowString3 = tokens.substring(row + 12, row + 13);
String rowString4 = tokens.substring(row + 18, row + 19);
String rowString5 = tokens.substring(row + 24, row + 25);
String rowString6 = tokens.substring(row + 30, row + 31);
String rowString7 = tokens.substring(row + 36, row + 37);
return "|" + rowString1 + "|" + rowString2 + "|"
+ rowString3 + "|" + rowString4 + "|" + rowString5
+ "|" + rowString6 + "|" + rowString7 + "|";
}
private void displayBoard(String extractRow) {
System.out.println(extractRow);
}
}