jordan
jordan

Reputation: 29

Read only numbers from scanner

Imagine there is Scanner passes any String input such as "11 22 a b 22" and the method should calculate the total sum of all of the numbers (55 for the mentiond example). I've coded something here but I'm not able to skip strings. Could anyone help me with that?

System.out.println("Please enter any words and/or numbers: ");
String kbdInput = kbd.nextLine();
Scanner input = new Scanner(kbdInput);
addNumbers(input);  

public static void addNumbers(Scanner input) {
    double sum = 0;
    while (input.hasNextDouble()) {
        double nextNumber = input.nextDouble();
        sum += nextNumber;
    }
    System.out.println("The total sum of the numbers from the file is " + sum);

}

Upvotes: 1

Views: 3467

Answers (1)

rgettman
rgettman

Reputation: 178263

To be able to bypass non-numeric input, you need to have your while loop look for any tokens still on the stream, not just doubles.

while (input.hasNext())

Then, inside, the while loop, see if the next token is a double with hasNextDouble. If not, you still need to consume the token with a call to next().

if (input.hasNextDouble())
{
   double nextNumber = input.nextDouble();
   sum += nextNumber;
}
else
{
   input.next();
}

Upvotes: 8

Related Questions