この課題に取り組んで 2 日間経ちましたが、とても苦労しています。私の課題では、次のようなプログラムを作成するよう求められています。
- ユーザーが実行を実行したい回数を尋ねます (例: 20 回のうち 3 回) (出力には、各試行間の比較が含まれている必要があります)
- ユーザーにコインを投げる回数を尋ねます (1000 回まで投げることができます)。
- 1 から 10 までの数字をランダムに生成し、すべての数字を配列に格納します
また、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.");
前もって感謝します!