【发布时间】:2018-01-26 23:02:53
【问题描述】:
因此,我正在尝试为我的计算机科学课程编写一个简单的程序,该程序从 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);
}
}
任何建议都会很棒。
【问题讨论】:
标签: java arrays dialog joptionpane