简体   繁体   English

使用用户Java输入列表的Max()方法

[英]Max()Method using inputted list from user-Java

enter image description here Once I enter in the list. 一旦在列表中输入图像说明 it will not display the maximum. 它不会显示最大值。 I tried to call in max in the last println it still did not work. 我试图在上一个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: "  );

}} 

How about 怎么样

Edit 编辑

// 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 );
//                                     ^^^^^^
      while (keyboard.hasNextDouble())
      {
         double input = keyboard.nextDouble();
         numbers.add(input);  
         if(input == -99)  break;
      }

Break will help you. 休息会帮助您。

Full Code with example: 完整代码示例:

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
    }
}

Output: 输出:

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

From the javadocs : Collections.max throws: javadocs :Collections.max引发:

NoSuchElementException - if the collection is empty. NoSuchElementException-如果集合为空。

Your list is empty. 您的清单是空的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM