所以我正在尝试为我的计算机科学课编写一个简单的程序,该程序从1-10中取一个随机数列表并计算每个数字的数量并打印到表中,所有这些都是在一个java对话框。这是我到目前为止所做的:
public class RandomArray {
public static void main(String[] args) {
String title, temp;
boolean ok;
int n = 0;
title = "Random Number Generator With Counts";
do {
ok = true;
temp = JOptionPane.showInputDialog(null, "Enter amount of random numbers to generate: ", title, 3);
try {
n = Integer.parseInt(temp);
}
catch (Exception e){
title = temp + " is not valid!";
ok = false;
}
}while(!ok);
int[] numbers = createArray(n);
int[] counts = countNumbers(numbers);
displayCounts(counts);
}
public static int[] createArray(int n) {
int[] numbers = new int[n];
int low = 1, high = 10;
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (int)(Math.random()*high) + low;
}
return numbers;
}
public static int[] countNumbers(int[] numbers) {
int[] counts = new int[10];
for(int i = 0; i < numbers.length; i++) {
counts[numbers[i]-1]++;
}
return counts;
}
public static void displayCounts(int[] counts) {
int message = 0;
for(int i = 0; i < counts.length; i++) {
message += counts[i];
}
JOptionPane.showMessageDialog(null, message, "Counts", 1);
}
}
任何建议都很棒。
答案 0 :(得分:0)
如果您正在尝试编写一个生成n个随机数的程序,每个程序在1到10之间,并显示频率表,显示随机生成的数字中每个数字出现的次数,然后尝试将displayCounts更改为:
public static void displayCounts(int[] counts) {
String message = "";
for(int i = 0; i < counts.length; i++) {
// added in:
if (counts[i] == 0)
continue;
message += (i+1) + " occurred " + counts[i] + " times \n";
}
JOptionPane.showMessageDialog(null, message, "Counts", 1);
}
counts是一个数组,它告诉你每个数字的生成次数。您只关心该频率值,如果它不是0.那么您可以将频率添加到显示字符串。
我希望这在某种程度上有所帮助:)