简体   繁体   English

为什么布尔值不会在 else 片段中更改其值?

[英]Why Boolean value doesn't change its value in else snippet?

Why boolean value doesn't change in else snippet, since overriding should happen in keepGoing variable in else body, what is the problem?为什么布尔值在else片段中不会改变,因为覆盖应该发生在 else 主体中的keepGoing变量中,有什么问题?

package com.company;
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);


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

This is comparing a StringBuilder to a String.这是将 StringBuilder 与 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.无论如何, 文档StringBuilder正在使用Object.equals() ,这意味着比较基于对象标识,而不是相等性。

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.但我不确定为什么首先使用StringBuilder Why not just为什么不只是

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

? ?

do you get an error?你有错误吗? If not, it may be because check does not equal yes.如果不是,可能是因为 check 不等于 yes。 You may just set keepGoing to true in the else statement and not worry about it.您可以在 else 语句中将 keepGoing 设置为 true 而不必担心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM