问题
I am currently working on a student project and everytime I get this error: ArrayIndexOutOfBoundsException: 7
. Can someone see where it occurs and how I can fix it? I know the code looks messy but its just for me. The size of the array is 7.
public void actionPerformed(ActionEvent e) {
if(c >= Playerlist.length) {
if(c >= wuerfelsummen.length) {
c = 0;
}
}
if(wuerfelsummen[c] == null) {
c++;
}
wuerfelsummen[c].setText(lbl_summe.getText());
pot.setCurrentPlayer(Playerlist[c]);
if(c >= Playerlist.length) {
c = 0;
} else {
c++;
//ARRAY_INDEX_OUT_OF_BOUNDS ERROR !!!!!!!!!!!!!!!!!!!!
while(wuerfelsummen[c] == null) {
if( c <= Playerlist.length) {
c++;
} else {
c = 0;
}
}
}
}
回答1:
if(c >= Playerlist.length)
{
c = 0;
}
else
{
c++;
//ARRAY_INDEX_OUT_OF_BOUNDS ERROR !!!!!!!!!!!!!!!!!!!!
while(wuerfelsummen[c] == null)
You are first checking if c is at most the last index of the array, and afterwards increment it by 1, possibly pushing it over that limit.
回答2:
Try it now, you have bad comparison, in loop:
public void actionPerformed(ActionEvent e) {
if(c >= Playerlist.length)
{
if(c >= wuerfelsummen.length)
{
c = 0;
}
}
System.out.println(c);
if(wuerfelsummen[c] == null)
{
c++;
}
System.out.println(c);
wuerfelsummen[c].setText(lbl_summe.getText());
lbl_summe.setText("0");
lbl_summe.setForeground(Color.black);
btnWerfeln.setEnabled(true);
pot.setCurrentPlayer(Playerlist[c]);
if(c >= Playerlist.length)
{
c = 0;
}
else
{
c++;
//ARRAY_INDEX_OUT_OF_BOUNDS ERROR !!!!!!!!!!!!!!!!!!!!
while(wuerfelsummen[c] == null)
{
if( c < Playerlist.length-1)
{
c++;
}
else
{
c = 0;
//ermittleGewinner(wuerfelsummen);
}
}
}
System.out.println(c);
//ermittleGewinner(wuerfelsummen);
}
});
回答3:
Currently you are incrementing the index at the end of the array, causing the program to go outside the bounds of the array. Therefore you should change...
if(c <= Playerlist.length)
{
c++;
}
...to...
if(c < Playerlist.length)
{
c++;
}
回答4:
problem in this string
if( c <= Playerlist.length) {
when
c = Playerlist.length
you will have a ARRAY_INDEX_OUT_OF_BOUNDS ERROR
来源:https://stackoverflow.com/questions/30596322/java-arrayindexoutofbound