gpt4 book ai didi

java - 字符串索引越界错误,找不到错误根源

转载 作者:行者123 更新时间:2023-12-02 00:33:08 26 4
gpt4 key购买 nike

当我尝试运行我的程序时,出现以下错误...

 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(Unknown Source)
at Woordzoeker.check(Woordzoeker.java:88)
at Woordzoeker.main(Woordzoeker.java:8)

我知道String可能超出了数组的边界,但我似乎不明白为什么。有人可以帮助我理解这个问题吗?

这是我的代码...

public class Woordzoeker {
public static String[] words = {"boom","ma","maat","kas","kast","as","boek","boot"};
public static String[][] grid = {{"b","o","e","k"},{"o","o","z","a"},{"o","j","o","s"},{"m","a","a","t"}};
public static String[][] gridz = new String[4][4];

public static void main(String[] args) {
for (int x=0; x < words.length-1; x++){
System.out.println(words[x] + " --> " + check(words[x],grid));
} // THIS IS LINE 8
System.out.println(isCorrectGrid(grid));
System.out.println(isCorrectWords(words));
}

public static int[] check(String word, String[][] grid){
int[] array = new int[3];
int y = 0;
for (int rij=0; rij < grid.length; rij++){
for (int kolom = 0;kolom < grid[rij].length; kolom++){
for (int x=0; x < words.length - 1; x++)
if (words[x].charAt(y) == (grid[rij][kolom].charAt(0))){ // THIS IS LINE 88
array[0] = rij;
array[1] = kolom; // slaat de begin coordinaten op
for (y = 0; y < words[x].length() - 1; y++){
if (words[x].charAt(y) == grid[rij + y][kolom].charAt(0)){
array[2] = 1;
}
if (words[x].charAt(y) == (grid[rij][kolom + y].charAt(0))){
array[2] = 2;
}
if (words[x].charAt(y) == (grid[rij + y][kolom + y].charAt(0))){
array[2] = 3;
}
}
}
}
}

最佳答案

也许你应该在last for之后清除y?

for (y = 0; y < words[x].length() - 1; y++){
if (words[x].charAt(y) == grid[rij + y][kolom].charAt(0)){
array[2] = 1;
}
if (words[x].charAt(y) == (grid[rij][kolom + y].charAt(0))){
array[2] = 2;
}
if (words[x].charAt(y) == (grid[rij + y][kolom + y].charAt(0))){
array[2] = 3;
}

}
y=0;

检查一下

关于java - 字符串索引越界错误,找不到错误根源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8472680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com