enter image description here一旦我输入列表。它不会显示最大值。我试图在上一个println中调用max,但仍然无法正常工作。

 ArrayList<Double> numbers = new ArrayList<Double>();

      Scanner keyboard = new Scanner(System.in);
      System.out.println("Please enter a list of numbers: ");

      while (keyboard.hasNextDouble())
      {
         double input = keyboard.nextDouble();
         numbers.add(input);
      }
    Double max = Collections.max(numbers);
        System.out.println("The Maximum is: "  );

}}

最佳答案

      while (keyboard.hasNextDouble())
      {
         double input = keyboard.nextDouble();
         numbers.add(input);
         if(input == -99)  break;
      }


休息会帮助您。

完整代码示例:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        ArrayList<Double> numbers = new ArrayList<Double>();

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter a list of numbers: ");

        while (keyboard.hasNextDouble()) {
            double input = keyboard.nextDouble();
            numbers.add(input);
            if (input == -99)
                break;
        }
        Double max = Collections.max(numbers);
        System.out.println("The Maximum is: " + max); // you have missed to add max here
    }
}


输出:

Please enter a list of numbers:
2
3
13
4
-99
The Maximum is: 13.0

10-08 00:44