mrgopher
mrgopher

Reputation: 11

Issues while error checking two variables with hasNext method

I am taking a Java class and I am stuck on an assignment using the hasNext command to error check two user entered variables to make sure they are numerical. This is what I have so far.

Scanner sc = new Scanner(System.in);

    String choice = "y";
    double firstside;
    double secondside;

    //obtain user input
    while (choice.equalsIgnoreCase("y")) {


    System.out.println("Enter First Side: ");
    if (sc.hasNextDouble()) {
        firstside = sc.nextDouble();

    } else {
        sc.nextLine();
        System.out.println("Please enter a numeric value and try again.");
        continue;
    }

    while (true){
    System.out.println("Enter Second Side: ");
    if (sc.hasNextDouble()) {
        secondside = sc.nextDouble();
        break;
    } else {
        sc.nextLine();
        System.out.println("Please enter a numeric value and try again.");
    }
    }

    //calculate results
    double hypotenusesquared = Math.pow(firstside, 2) + Math.pow(secondside, 2);
    double hypotenuse = Math.sqrt(hypotenusesquared);

    //display results
    String output = "Hypotenuse = " + hypotenuse;
    System.out.println(output);
    System.out.println("Would you like to continue? Y/N?");
    choice = sc.next();
}

} }

The output I am receiving when there is an error is:

Please enter a numeric value and try again. Enter First Side: Please enter a numeric value and try again. Enter First Side:

I intend to only receive:

Please enter a numeric value and try again. Enter First Side:

Upvotes: 1

Views: 202

Answers (1)

Raman Sahasi
Raman Sahasi

Reputation: 31901

That's because the continue; of your second statement makes your program to go back to the first line of while loop (next iteration).

To overcome it, you should put the second side scan statement in it's own while loop. Something like this:

System.out.println("Enter Second Side: "); //move this inside below loop if you want to prompt user for each invalid input.

while(true) {
    if (sc.hasNextDouble()) {
        secondside = sc.nextDouble();
        break; //if we get double value, then break this loop;
    } else {
        sc.nextLine();
        continue; //you can remove this continue
    }
}

Upvotes: 1

Related Questions