Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do-while statement Java

I am new to programming. I have difficulties understanding this bit of code:

public static boolean onCampus(String name)
{
    boolean invalidResponse = true;
    do{
    System.out.println("Is "+name+ " living on campus? (yes/no)");
    String response = in.nextLine();
    if(response.equalsIgnoreCase("yes"))
        return true;
    else if (response.equalsIgnoreCase("no"))
        return false;
    else
        System.out.println("Invalid response.");
    } while(invalidResponse);
    return false;
}

What I don't get is where is invalidResponse assigned false in case the user enter an acceptable response? And what is that last return false;? Why is it after the do-while statement?

like image 682
ocram Avatar asked Feb 21 '26 18:02

ocram


2 Answers

This is somewhat of an anti-pattern - the loop is infinite, and will never terminate "properly". Instead, once you get a valid response, you'll simply call return, and exit the method, thus terminating the loop.

The return false after the loop is a compilation limitation. In java, if the method returns a value, every conceivable branch must contain a return statement (or a throw statement, to be precise). In compile time, Java doesn't "know" that the loop may never be terminated, so it forces you to have a return statement in that branch (i.e., assuming the loop terminates without the if or else if branches being executed).

like image 183
Mureinik Avatar answered Feb 23 '26 06:02

Mureinik


The last "return false;" is just there so that the compiler will not complain, it is unreachable code. Because your return type is boolean, your code must return true or false for all cases. "invalidResponse" is never assigned to false so your loop will run infinitely until the user enters either yes or no in which case it returns the boolean and exits the function.

like image 21
J. Nutt Avatar answered Feb 23 '26 06:02

J. Nutt