user2565646
user2565646

Reputation: 3

Java - how to scan a token and check that token after it exists and is a double

I'm having trouble with the following program. I would like input to have the form "value" followed by a double value, and if the input is not of this form, I want to return an error message. Essentially, I want to check that the first word is "value" (if not, return "false"), then I want to check that there is another token and that this token is a double (if this is not the case, return false). I'm having trouble, though, because if I just enter "value" as input, the program just waits for me to enter another token, instead of returning "Value expected." like I want it to. Here's the code:

import java.util.Scanner;
public class scanCheck {
    public static void main(String[] args) {

Scanner kb = new Scanner(System.in);
double a;
String str;

str = kb.next();
if (!str.equals("value"))
    System.out.print("Invalid format.");
else {
    if (kb.hasNext())
        if (kb.hasNextDouble())
            a = kb.nextDouble();
        else
            System.out.println("Value expected.");
    else 
        System.out.println("Value expected.");
    }
    }
}

Thank you!

Upvotes: 0

Views: 2501

Answers (2)

ajay.patel
ajay.patel

Reputation: 1967

Try this:

    str = kb.next();
    if (!str.equals("value")){
        System.out.print("Invalid format.");
        System.exit(0);
       }

Upvotes: 0

Marco Corona
Marco Corona

Reputation: 812

Since you are waiting for user commands, kb.hasNext() will never really evaluate to false. So this code is acting how it is supposed to. If you want "Value expected" to appear after the user types value, move the println statement.

else {
    System.out.println("Value expected.");
    if (kb.hasNextDouble()){
         a = kb.nextDouble();
    }else {
         System.out.println("Value expected.");
    }

Upvotes: 1

Related Questions