0
嗨我正在寫一個程序功課,在高爾頓框中顯示球的路徑高爾頓盒概率
我的計劃至今挑選你要多少球下降,在盒子底部的槽的數量,並顯示你球隨機路徑。
我遇到的問題是,如果球的數量大於或等於插槽的數量框中的程序不充分磨合,我得到這個錯誤
Enter the amount of balls to drop:
8
Enter the amount of slots:
8
LRLLRRR
RLRLLLR
RLRLLLL
RLLLLRR
RLRRRLL
RRLRRRR
LLLRRRR
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at Set_8_P6_21.main(Set_8_P6_21.java:35)
所以我想知道是否有人能解釋爲什麼會發生這種情況......謝謝!
import java.util.Scanner;
public class Set_8_P6_21 {
public static void main(String[] args) {
int balls, slots;
System.out.println("Enter the amount of balls to drop: ");
Scanner input = new Scanner(System.in);
balls = input.nextInt();
System.out.println("Enter the amount of slots: ");
slots = input.nextInt();
char[] arrayslot = new char[slots-1];
for (int i = 0; i < balls; i++) {
System.out.println();
for (int j = 0; j < slots-1; j++) {
double k = Math.random();
if (k < 0.5)
arrayslot[i] = 'L';
else if (k >= 0.5)
arrayslot[i] = 'R';
System.out.print(arrayslot[i]);
}
}
}
}
如果有錯誤消息,請將其發佈到此處,而不是其他地方的屏幕截圖。 – 2014-11-24 00:09:26
你聲明'slotslot'的長度爲'slots-1',但是你可以用'arrayslot [i]'來訪問它,其中'i'從'0'到'balls-1'(見你的第一個'for '循環)。 – Blorgbeard 2014-11-24 00:09:40
僅供參考:不要使用片段按鈕添加不可執行的代碼塊。您只需要{}'按鈕。 – Blorgbeard 2014-11-24 00:13:23