How do I get the max and min values from a set of numbers entered?

后端 未结 8 1022
终归单人心
终归单人心 2020-11-28 15:52

Below is what I have so far:

I don\'t know how to exclude 0 as a min number though. The assignment asks for 0 to be the exit number so I need to have the lowest numb

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 16:40

    I tried to optimize solution by handling user input exceptions.

    public class Solution {
        private static Integer TERMINATION_VALUE = 0;
        public static void main(String[] args) {
            Integer value = null;
            Integer minimum = Integer.MAX_VALUE;
            Integer maximum = Integer.MIN_VALUE;
            Scanner scanner = new Scanner(System.in);
            while (value != TERMINATION_VALUE) {
                Boolean inputValid = Boolean.TRUE;
                try {
                    System.out.print("Enter a value: ");
                    value = scanner.nextInt();
                } catch (InputMismatchException e) {
                    System.out.println("Value must be greater or equal to " + Integer.MIN_VALUE + " and less or equals to " + Integer.MAX_VALUE );
                    inputValid = Boolean.FALSE;
                    scanner.next();
                }
                if(Boolean.TRUE.equals(inputValid)){
                    minimum = Math.min(minimum, value);
                    maximum = Math.max(maximum, value);
                }
            }
            if(TERMINATION_VALUE.equals(minimum) || TERMINATION_VALUE.equals(maximum)){
                System.out.println("There is not any valid input.");
            } else{
                System.out.println("Minimum: " + minimum);
                System.out.println("Maximum: " + maximum);
            }
            scanner.close();
        }
    }
    
    

提交回复
热议问题