(Java)如何跟踪用户确定最小和最大输入的数字 [英] (Java) How to Keep Track of Numbers Entered by User for Determining Min and Max

查看:69
本文介绍了(Java)如何跟踪用户确定最小和最大输入的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个作业分配,要求我使用输入对话框要求最终用户输入数字,将String解析为int,然后使用确认对话框询问用户是否要输入另一个数字.如果单击是",程序将循环运行,一旦单击否",它将获取所有输入的数字并确定最小值和最大值.如何跟踪所有输入的数字而无需声明多个变量来保存它们(因为从技术上讲,用户可以输入无限数量的数字)?

I have a homework assignment that is asking me to use an input dialog to ask the end user to enter a number, parse that String to an int, and then use a confirm dialog to ask if the user wants to enter another number. If they click yes, the program loops, and once they hit no, it takes all of the entered numbers and determines the min and max. How do I keep track of all the entered numbers without declaring multiple variables to hold them (since the user can technically enter an infinite amount of numbers)?

我对编程很陌生.我一直在搜寻教科书,并且浏览过Stack Overflow以查找自己的具体问题,但至少在Java中什么也没发现.

I'm very new to programming. I've been scouring my textbook, and I've browsed Stack Overflow to find my specific problem and haven't found anything, at least in Java.

    {
        int yes = JOptionPane.YES_OPTION;

        do
        {
            String numberstring = JOptionPane.showInputDialog("Enter a "
                    + "number: ");
            int number = Integer.parseInt(numberstring);

            yes = JOptionPane.showConfirmDialog(null, "Do you want to enter"
                    + " another number?", "MinMax", JOptionPane.YES_OPTION);
        }
        while (yes == JOptionPane.YES_OPTION);

        JOptionPane.showMessageDialog(null, "The min is " + min + " and the"
                + " max is " + max);
    }

我没有收到任何错误,我只是不知道如何保存来自用户的可能无限数量的条目,因为程序会循环直到用户单击否".

I'm not exactly receiving any errors, I just have no idea how to hold a possibly infinite amount of entries from the user since the program loops until the user clicks "no".

推荐答案

您可以执行以下操作:

{
    int yes = JOptionPane.YES_OPTION;
    List<Integer> list=new ArrayList<Integer>();

    do
    {
        String numberstring = JOptionPane.showInputDialog("Enter a "
                + "number: ");
        int number = Integer.parseInt(numberstring);

        list.add(number);

        yes = JOptionPane.showConfirmDialog(null, "Do you want to enter"
                + " another number?", "MinMax", JOptionPane.YES_OPTION);
    }
    while (yes == JOptionPane.YES_OPTION);

    int min = list.get(0), max = list.get(0);
    for (int i = 1; i < list.size(); i++) {
        if (min > list.get(i))
            min = list.get(i);
        if (max < list.get(i))
            max = list.get(i);
    }

    JOptionPane.showMessageDialog(null, "The min is " + min + " and the"
            + " max is " + max);
}

这篇关于(Java)如何跟踪用户确定最小和最大输入的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆