(JAVA) Break 命令在不应该执行的时候执行

(JAVA) Break command is executing when it shouldn't

我刚开始学习Java,我有点迷茫为什么我的代码底部的"break"命令被执行了。

import java.util.Scanner;

public class GradeValues {

    private static Scanner scanner;

    public static void main(String[] args) {
        boolean keepGoing = true;
        String grade; // initializing variable for grade

        while(keepGoing = true){
            System.out.println("What percentage did you get? ");  //Ask User the question
            scanner = new Scanner(System.in); //starting the scanner 
            grade = scanner.nextLine();  //storing user input of percentage

            int percentage = Integer.parseInt(grade);  //converting string to a int

            if(percentage >= 80 && percentage <= 100){
                System.out.println("Your grade is an A!  Awesome job!");
            }else if(percentage >= 70 && percentage <= 79){
                System.out.println("Your grade is an B!  Nice work!");
            }else if(percentage >= 60 && percentage <= 69){
                System.out.println("Your grade is an C!  That's average. =( ");
            }else if(percentage >= 50 && percentage <= 59){
                System.out.println("Your grade is an D!  Come on man, you can do better.");
            }else if(percentage < 50){
                System.out.println("Your grade is an F!  You need to hit the books again and try again.");
            }else{
                System.out.println("I think you type the wrong value.");
            }

            System.out.println("Would you like to check another grade?");  //Asking user if they want to do it again
            Scanner choice = new Scanner(System.in);  //Gets user input
            String answer = choice.nextLine();  // Stores input in variable "answer"
            if(answer == "yes"){
                keepGoing = true;  //While loop should keep going

            }else{
                keepGoing = false;  //While loop should stop
                break;  //this should stop program
            }
        }
    }
}

考虑到 keepGoing 布尔变量仍然为真(如果用户键入 'yes'),应用程序仍然会因为 else 语句中的中断而停止。谁能告诉我为什么会这样以及如何解决这个问题?

answer是一个String,是一个对象类型。您应该将其与 equals 方法进行比较,而不是 == 运算符:

if (answer.equals("yes")) {
    // etc.

您不能将字符串与 == 运算符进行比较。

为了正确比较字符串,您必须使用 equals 方法。

例如,将代码中的 if/else 语句替换为:

if("yes".equals(answer)){
    keepGoing = true;  //While loop should keep going

}else{
    keepGoing = false;  //While loop should stop
    break;  //this should stop program 
}

我想如果不是拼写错误,那么您的 while 条件不正确 while(keepGoing = true) ... 应该是 while(keepGoing == true)while(keepGoing)。这样你就不需要在最后休息了。就像其他答案中建议的那样,请使用 equals 来比较字符串。