我已經在這項任務上工作了兩天,現在我度過了這麼艱難的時刻! 我的任務要求我創建一個程序:ArrayIndexOutOfBoundsException,數組和整數的計數發生
- 詢問用戶想多少次執行運行(如20的3次 翻轉)(輸出應該有每次試驗之間的比較)
- 問他有多少次想他的硬幣翻轉用戶(他可以 翻轉多達1000次)
- 隨機生成一個數組1十, 存儲中的所有號碼之間的數字
它還必須顯示10個數字中每個數字出現的次數,最多顯示的數字,如果偶數是正數,而奇數是尾數,那麼硬幣的哪一面最多。 請幫助我,我已經嘗試編寫代碼,但我有這麼難的時間,我真的很緊張!
這裏是我的代碼:
import java.io.*;
import java.util.Random;
public class ColCoin
{
public static void main(String[] args) throws IOException
{
//set variables
String timesString;
String run;
int times;
int runNum;
int i = 0;
int x;
//input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//random object
Random r = new Random();
System.out.print("How many times would you like to perform a run through the flips? ");
run = br.readLine();
runNum = Integer.parseInt(run);
do
{
//ask how many times the coin will flip
System.out.print("Please input the amount of times you would like to flip the coin (1-1000): ");
timesString = br.readLine();
//convert String into an integer
times = Integer.parseInt(timesString);
if((times > 1000)||(times < 1))
{
System.out.println("ERROR! Must input an integer between 1 and 1000!");
}
System.out.println("You chose to flip the coin " + times + " times.");
} while((times > 1000)||(times < 1));
for(x=0; x <= runNum; x++)
{
//create array
int flip[] = new int[times];
int countArray[] = new int[i];
//create a new variable
int storeTime;
for(storeTime = 0; storeTime < flip.length; storeTime++)
{
flip[storeTime] = r.nextInt(10) + 1;
// the line above stores a random integer between 1 and 10 within the current index
System.out.println("Flip number " + (storeTime+1) + " = " + flip[storeTime]);
}
//display the counts
for(i=0; i < 10; i++)
{
System.out.println("The occurences of each of the numbers is: ");
System.out.println((i+1) + " appears " + countArray[i] + "times.");
}
}
}
}
它還線64上給了一個ArrayIndexOutOfBoundsException錯誤,我不知道爲什麼:
System.out.println((i+1) + " appears " + countArray[i] + "times.");
提前感謝!
當你做int countArray [] = new int [i]時,我的值是多少?這就是你的陣列有多大。當你得到例外時,我的價值是多少? –
不要爲全局聲明循環索引值。你完全迷惑自己。分配數組時,「i」爲零,然後在循環中增加它。 –
請注意,除非賦值明確指定它,否則根本不需要flip數組,因爲您顯示的唯一部分是計數,並且您可以直接通過int result = r.nextInt(10 )+ 1; flipCounts [結果] ++;'。 – Boann