【问题标题】:Why won't all the pieces of my array display in a java dialog box?为什么我的数组的所有部分都不会显示在 java 对话框中?
【发布时间】: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


    【解决方案1】:

    如果您正在尝试编写一个生成 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。那么您可以将频率添加到您的显示字符串中。

    我希望这在某种程度上有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      相关资源
      最近更新 更多