我目前有一个问题,不知道为什么会这样做但是我使用单选按钮让用户选择他们想要循环运行的次数。
所以问题是当我运行它时,随机数没有被存储到数组中我得到了一个边界异常:
下面;
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
public class SortingProgramView extends FrameView {
int numOfEntries;
int[] numbers = new int[0];
private void sortButtonActionPerformed(java.awt.event.ActionEvent evt) {
for (int i = 0; i <= numOfEntries-1 ; i++)
{
numbers[i]= (-10000) + (int)(Math.random()*20001);
}
unsortedInfo();
}
private void unsortedInfo(){
unsortedOutput.setText(" ");
for (int j=0;j<=numOfEntries;j++){
unsortedOutput.append(+numbers[j]+"\n");
}
}
private void tenEntriesActionPerformed(java.awt.event.ActionEvent evt) {
numOfEntries = 10;
numbers = new int[numOfEntries];
}
private void hundredEntriesActionPerformed(java.awt.event.ActionEvent evt) {
numOfEntries = 100;
numbers = new int[numOfEntries];
}
private void thousandEntriesActionPerformed(java.awt.event.ActionEvent evt) {
numOfEntries = 1000;
numbers = new int[numOfEntries];
}
private void fiveThousandEntriesActionPerformed(java.awt.event.ActionEvent evt) {
numOfEntries = 5000;
numbers = new int[numOfEntries];
}
}
答案 0 :(得分:1)
这一行:
int[] numbers = new int[numOfEntries];
在任何这些来电之前发生:tenEntriesActionPerformed
,hundredEntriesActionPerformed
等。
您应该将这些方法更改为:
private void tenEntriesActionPerformed(java.awt.event.ActionEvent evt) {
numOfEntries = 10;
numbers = new int[numOfEntries];//resize the array
}