[英]Need help to create an array of randomly generated numbers within a range and then displaying the frequency of each number in that range
正如標題所暗示的那樣,我在編寫可以按要求執行的代碼時遇到了麻煩。 我所擁有的是:
public static void main(String[] args) {
int[] runs = new int[24];
for(int i = 0; i < runs.length; i++) {
runs[i] = (int)(Math.random()*3 + 1);
int count = 1;
for (int j = i+1; j<i;j++) {
if (runs[i] == runs[j]) {
count++;
}
}
System.out.println(runs[i] + " " + count);
}
}
但是,每當我運行我的程序時,它只會列出隨機生成的數字,然后在它們旁邊列出一個 1。 任何幫助表示贊賞,謝謝!
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
for(int i = 0; i < runs.length; i++) {
runs[i] = (int)(Math.random()*3 + 1);
if (runs[i] == 1) {
count1++;
} else if (runs[i] == 2) {
count2++;
} else if (runs[i] == 3) {
count3++;
} else {
count4++;
}
}
System.out.println("1's Frequency is: " + count1);
System.out.println("2's Frequency is: " + count2);
System.out.println("3's Frequency is: " + count3);
System.out.println("4's Frequency is: " + count4);
我上面提供的代碼塊應該可以工作。 您的代碼的問題之一是在搜索數組以查找每個數字的頻率之前,您沒有生成數組中的所有數字。 此外,代碼嵌套循環中的代碼塊不會完成找出每個數字頻率的任務。
我在這里所做的是它通過循環並為數組中的每個空格分配一個隨機數。 並且,每次它分配一個隨機數時,它還通過一系列條件語句來計算或增加范圍內每個數字的頻率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.