Home > Software design >  Why Boolean value doesn't change its value in else snippet?
Why Boolean value doesn't change its value in else snippet?

Time:10-16

Why Boolean value doesn't change its value in else snippet, since overriding should happen in keepGoing variable in else body, what is the problem?

import java.util.Scanner;
public class Main {

    public static void main(String[] name) {
        Scanner display = new Scanner(System.in);
        StringBuilder check = new StringBuilder();
        boolean keepGoing = false;

        do{
        System.out.println("please insert your name to check if it is valid or not:");
        String Name = display.next();

            if(Name.equals("alex")) {
                System.out.println("it is valid");
                keepGoing = false;
            }


            else {
                System.out.println("it is not valid");
                System.out.println("do you want to continue: yes/no");
                check.append(display.next());
                keepGoing = check.equals("yes");
            }
        } while(keepGoing);


    }
}```

CodePudding user response:

keepGoing = check.equals("yes");

This is comparing a StringBuilder to a String. They are not going to be equal.

In any case, the documentation says that StringBuilder is using Object.equals(), which means the comparison is based on object identity, not equality.

The closest match to what I infer as your intent would be

keepGoing = check.toString().equals("yes");

but I'm not really sure why a StringBuilder is being used in the first place. Why not just

String answer = display.next();
keepGoing = answer.equals.("yes");

?

CodePudding user response:

do you get an error? If not, it may be because check does not equal yes. You may just set keepGoing to true in the else statement and not worry about it.

  • Related