[英]IndexOutOfBoundsException issue in java arraylist
The line in which the error occurs is indicated.指示发生错误的行。 The program consists of searching for the repeated characters and saving them in a list.该程序包括搜索重复的字符并将它们保存在一个列表中。 In that list of type "letter", the letter will be saved in char format and the counter of the letters found.在“字母”类型的列表中,该字母将以字符格式和找到的字母的计数器保存。
ArrayList<letter> list = new ArrayList<letter>();
String comb = "";
comb="hhhoofdpsdshodss";
for(int i = 1; i<comb.length(); i++){ //16
boolean finded = false;
for(int j=0; j < i && finded == false; j++){
if(comb.charAt(j)==comb.charAt(i)){
try{
list.get(j).upCounter(); //Error here
}catch(Exception E){
System.out.println(E);
}
finded = true;
}
}
if(finded==false){
list.add(new letter(comb.charAt(i)));
}
}
for(int i = 0; i<list.size() ; i++){
System.out.println((char)list.get(i).getLetter() + ": " + list.get(i).getCounter());
}
Here is the class "letter"这是“信”类
class letter{
private char let;
int counter= 0;
public letter(char character){
let=character;
counter++;
}
public int getCounter(){
return counter;
}
public void upCounter(){
counter++;
}
public int getLetter(){
return let;
}
}
The issue is that when you begin, list
is empty.问题是当你开始时, list
是空的。 When you try to access elements, it will always try to access a value that is not there, but because there is no element, there will be an error.当你尝试访问元素时,它总是会尝试访问一个不存在的值,但是因为没有元素,所以会报错。 Your ArrayList must have some values in it to begin.您的 ArrayList 必须有一些值才能开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.