Search code examples
javaloopsmaxminjoptionpane

(Java) How to Keep Track of Numbers Entered by User for Determining Min and Max


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)?

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".


Solution

  • You can do it as follows:

    {
        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);
    }