Reputation: 18875
I am trying to use a Scanner object to read keyboard input (double type numbers). The program compiles, but it can only take two numbers. Below is my code, please help me find the reason. Thank you!
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
ArrayList<String> container = new ArrayList<String>();
double number = 0;
System.out.println("Type in the polynomials in increasing powers:");
while (!keyboard.nextLine().isEmpty())
{
// number = keyboard.nextDouble();
try {
number = keyboard.nextDouble();
} catch(Exception e) // throw exception if the user input is not of double type
{
System.out.println("Invalid input");
}
container.add("-" + number);
}
Upvotes: 0
Views: 340
Reputation: 279970
The method call nextLine()
in
while (!keyboard.nextLine().isEmpty())
will consume the first double
value you enter. This
number = keyboard.nextDouble();
will then consume the second one.
When the loop iterates again, keyboard.nextLine()
will consume the trailing end of line characters which it will trim()
. isEmpty()
will therefore return true
.
The solution if you want to enter a number, press enter, and keep entering numbers is to read the line as a String
and use Double.parseDouble(String)
to get a double
value.
Otherwise, you can also use
while (keyboard.hasNextDouble()) {
number = keyboard.nextDouble();
System.out.println(number);
...
}
And enter your numbers on a single line separated by spaces
22.0 45.6 123.123123 -61.31 -
Use a random non-numerical character at the end to tell it input is done. The above prints
22.0
45.6
123.123123
-61.31
and stops.
Upvotes: 2