Reputation:
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
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
Reputation: 29130
while (keyboard.hasNextDouble())
{
double input = keyboard.nextDouble();
numbers.add(input);
if(input == -99) break;
}
Break will help you.
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