smallest and largest of the inputs

前端 未结 3 1401
无人共我
无人共我 2020-12-22 12:50

I was assigned to write a program that read a sequence of integer inputs and print -the smallest and largest of the inputs -and the number of even and odd inputs

I f

相关标签:
3条回答
  • 2020-12-22 12:56

    Keep track of the smallest value in the same manner.

    public static void main(String args[])
    {
        Scanner a = new Scanner (System.in);
        System.out.println("Enter inputs (This program calculates the largest and smallest input):");
    
        double firstInput = a.nextDouble();
        double largest = firstInput;
        double smallest = firstInput;
        while (a.hasNextDouble())
        { 
            double input = a.nextDouble();
            if (input > largest)
            {
                largest = input;
            }
            if (input < smallest)
            {
                smallest = input;
            }
        }
    
        System.out.println("Largest: " + largest);
        System.out.println("Smallest: " + smallest);
        }
    }
    
    0 讨论(0)
  • 2020-12-22 12:59

    The simplest solution would be use something like Math.min and Math.max

    double largest = a.nextDouble();
    double smallest = largest;
    while (a.hasNextDouble()) {
        double input = a.nextDouble();
        largest = Math.max(largest, input);
        smallest = Math.min(smallest, input);
    }
    
    0 讨论(0)
  • 2020-12-22 13:12
    double largest = a.nextDouble();
    double smallest = largest;
    while (a.hasNextDouble()) {
        double input = a.nextDouble();
        if (input > largest) {
            largest = input;
        }
        if (input < smallest) {
            smallest = input;
        }
    }
    
    0 讨论(0)
提交回复
热议问题