Max()方法使用来自user-Java的输入列表

时间:2016-04-21 02:27:25

标签: java max

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: "  );

}} 

3 个答案:

答案 0 :(得分:1)

怎么样

修改

// check to make sure that numbers has some elements

if (numbers.size () <= 0) {
   // some message
   return;
}
Double max = Collections.max(numbers);
System.out.println("The Maximum is: "  + max );
//                                     ^^^^^^

答案 1 :(得分:0)

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

输出:

find . -type d | sort | xargs -n1 -I{} bash -c "find {} -type f -maxdepth 1 -executable | sort -r"

答案 2 :(得分:0)

来自javadocs: Collections.max抛出:

  

NoSuchElementException - 如果集合为空。

您的清单是空的。