Java 如何修复越界索引错误?
固定的: 我删除了while循环并添加了Java 如何修复越界索引错误?,java,arrays,list,indexoutofboundsexception,stringbuilder,Java,Arrays,List,Indexoutofboundsexception,Stringbuilder,固定的: 我删除了while循环并添加了 if (num.contains(count) == true) { freq = Collections.frequency(num, count); for (int k = 0; k < freq; k++) { sb.append(temp); } } if(num.conta
if (num.contains(count) == true) {
freq = Collections.frequency(num, count);
for (int k = 0; k < freq; k++) {
sb.append(temp);
}
}
if(num.contains(count)==true){
freq=Collections.frequency(num,count);
对于(int k=0;k
我正在尝试向一个单词中添加一个随机的(介于0-8之间)额外的字母副本。例子。。。Doe可能会变成DooEE或Doess
我的函数有时会工作,但总是会因越界索引错误而崩溃
我假设我需要在某个时刻检查ArrayList中的空值。我试图用和if来包装我的while语句,以检查它,但没有任何改进。有什么建议吗
private static String addLetters(String word) {
StringBuilder sb = new StringBuilder(word.length());
String[] apart = word.split("");
int rand = (int)(Math.random() * 8);
int ran, goUp;
int count = 0;
List<Integer> num = new ArrayList<>();
for (int i = 0; i < rand; i++) {
ran = (int)(Math.random() * word.length());
num.add(ran);
}
Collections.sort(num);
for (int temp : num) {
System.out.println(temp);
}
for (String temp: apart) {
goUp = count;
sb.append(temp);
System.out.printf("String so far: %s\n", sb.toString());
System.out.printf("OUTSIDE: count: %d, goUp: %d\n", count, goUp);
/*
Removed the while loop and added in the above code using collections, works as intended now.
*/
while (count == num.get(goUp)) {
System.out.printf("INSIDE: count: %d, goUp: %d\n", count, num.get(goUp));
sb.append(temp);
System.out.printf("String ADD extra: %s\n", sb.toString());
goUp++;
}
count++;
}
return sb.toString();
}
私有静态字符串addLetters(字符串字){
StringBuilder sb=新的StringBuilder(word.length());
字符串[]分开=字。分开(“”);
int rand=(int)(Math.random()*8);
int-ran,goUp;
整数计数=0;
List num=new ArrayList();
对于(int i=0;i
您的循环在单词输入(大小)上,您在num(rand部分)上执行num.get(goUp)
如果单词输入大小大于rand大小,则出现此错误(第41行):
数组索引越界错误通常应该通过修复错误来处理 你的逻辑太混乱了,我不确定你的代码应该如何工作。但是,我确实看到了您的崩溃:
将num数组的用途与while语句的条件中使用的用途进行比较,如填充方式所示。很明显,您正在以两种不同的方式使用它。是的,我知道,已修复它。
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(ArrayList.java:638)
at java.util.ArrayList.get(ArrayList.java:414)
at com.sgr.games.Stack.addLetters(Stack.java:41)
at com.sgr.games.Stack.main(Stack.java:10)
L39 System.out.printf("OUTSIDE: count: %d, goUp: %d\n", count, goUp);
L40
L41 while (count == num.get(goUp)) {
L42 System.out.printf("INSIDE: count: %d, goUp: %d\n", count, num.get(goUp));