我编写了一个程序,根据用户选择要删除的列来显示放入板中的令牌。我收到运行时错误
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…
当我运行该程序时,我有点迷失了我可能出错的地方。
我的代码是:
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);
}
}
答案 0 :(得分:0)
跟踪中的以下行:java.lang.String.substring(Unknown Source)
表示问题出在tokens.substring()
这是因为令牌的长度少于您尝试提取的子串。您可以打印令牌的长度并自行检查