Sruli
Sruli

Reputation: 365

Having trouble with in.nextDouble()

I'm trying to use the in.nextDouble() method in the below program designed to compute the average of a few numbers.

import java.util.Scanner;

public class Average
{
public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    double value;
    int count = 0;
    double sum = 0;
    System.out.print("Enter a value, Q to quit: ");
    while (in.hasNextDouble())
    {
            value = in.nextDouble();
            sum = sum + value;
            count++;
            System.out.print("Enter a value, Q to quit: ");
    }
    double average = sum / count;
    System.out.printf("Average: %.2f\n", average);
}
}

This code works although I don't understand why. When I first use while(in.hasNextDouble()) I haven't initialised in to anything so why does the loop work?

Upvotes: 3

Views: 992

Answers (1)

Codebender
Codebender

Reputation: 14438

When you call in.hasNextXXX() when there is no input, the Scanner waits for input.

So, it waits for you to enter a value in the first case.

It will exit as soon as you enter something other than a double (and press enter).

The doc of Scanner#hasNext()

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.

This is true for all hasNextXXX() operations.

Upvotes: 5

Related Questions