我正在尝试制作字母汤,但我不断收到“字符串索引超出范围”错误:
线程“main”中的异常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:4 在 java.lang.String.substring(String.java:1963)
当我尝试动态插入子字符串时,(每个字符应位于数组的一个位置)。 (fRandom 的意思是将每个单词插入数组的随机行中)。
到目前为止,这是我的代码:
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
Random random = new Random();
int i; int j; int fRandom;
int counter = 0; String word = "";
int x = 0; int y = 0;
String matrix[][] = new String[20][20];
for(i = 0; i < 20; i++) {
fRandom = random.nextInt(19);
for(j = 0; j < 20; j++) {
if(counter < 5){
System.out.println("Enter word between 3 and 5 characters");
word = read.next();
while(word.length() > 5 || word.length() < 3){
System.out.println("Must have between 3 and 5 characters");
word = read.next();
}
}
matrix[fRandom][j] = word.substring(x++, y++);
counter += 1;
}
}
每当我使用静态子字符串 (0,1) 运行程序时,它不会抛出任何错误,如果我使用仅具有起始索引的子字符串 (0),整个单词将进入数组的每个位置。 我尝试在代码的不同阶段打印以查看问题所在,并将其缩小到 substring() 方法,其他一切正常。 我也试过将 fRandom 更改为“fRandom = random.nextInt(20)”,但它会引发错误。 感谢您的建议!