简体   繁体   中英

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.

 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:

NoSuchElementException - if the collection is empty.

Your list is empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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