Bartosz Kubacki Bartosz Kubacki - 1 month ago 10
Java Question

Do..While loop keeps repeating, Scanner issue

do {
System.out.println("Set the A param: ");
if(input.hasNextDouble() == true) {
A = input.nextDouble();
if(A == 0) {
System.out.println("Param A cannot be a 0!");
}
} else if(input.hasNextDouble() == false) {
System.out.println("Param A must be a number!");
}
} while(A == 0 || input.hasNextDouble() == false);


Hello, I'm really new in Java and I found an obstacle I can't resolve by myself.

Everything is okay until I enter some letter instead of number, then this do..while loop keeps repeating itself.

After some search I suppose this might be a problem with a Scanner buffer becouse I should clear it before every loop with
input.nextLine()
but I don't really know where in code should I put it.

Thanks for any help.

Answer

Seems like you just want to get the value of A which should be not equal to 0 . Read comments

double A=0;
do {   
    System.out.println("Set the A param: ");
    if(input.hasNextDouble() == true) { //check for valid value 
        A = input.nextDouble();
        if(A == 0) {
            System.out.println("Param A cannot be a 0!");
        }
    } else{ // no valid value found , print msg and jump over the previous input
        input.next();
        System.out.println("Param A must be a number!");
    }
} while(A == 0); // just check , if the desired value is received 
Comments