user6233184
user6233184

Reputation:

Max()Method using inputted list from user-Java

enter image description hereOnce 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: "  );

}} 

Upvotes: 0

Views: 59

Answers (3)

Scary Wombat
Scary Wombat

Reputation: 44814

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 );
//                                     ^^^^^^

Upvotes: 1

SkyWalker
SkyWalker

Reputation: 29130

      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

Upvotes: 0

Roman
Roman

Reputation: 3198

From the javadocs: Collections.max throws:

NoSuchElementException - if the collection is empty.

Your list is empty.

Upvotes: 0

Related Questions