用具有逻辑 && (AND) 运算符的单个 if 语句替换嵌套的 if 语句,以实现相同的输出

问题描述 投票:0回答:1

下面是演示考试分数的嵌套 if 语句的代码:

public class NestIfExample {

    public static void main(String[] args) {
        Scanner inputDevice = new Scanner(System.in);
        
        // Asking the user to input their score
        System.out.print("Enter your score: ");
        int score = inputDevice.nextInt();

        // Outer if statement
        if (score >= 50) {
            System.out.println("You passed the exam!");

            // Inner if statement - only checked if the score is 50 or more
            if (score >= 80) {
                System.out.println("Great job! You scored in the top range.");
            } else {
                System.out.println("Good effort, but there's room for improvement.");
            }
        } else {
            System.out.println("Unfortunately, you did not pass. Try again next time.");
        }
    }
}

如何将此嵌套 if 语句更改为具有逻辑 && (AND) 运算符的单个 if 语句并实现相同的输出?

这是我尝试过的。我通过连接两个条件并使它们成为一个条件(分数 >= 80 && 分数 >= 50)来创建一个 if 语句。 我不确定这是否正确。请告诉我。

public static void main(String[] args) {
    Scanner inputDevice = new Scanner(System.in);
    
    // Asking the user to input their score
    System.out.print("Enter your score: ");
    int score = inputDevice.nextInt();

    // Single if statement using logical AND (&&) operator
    if (score >= 80 && score >= 50) {
        System.out.println("You passed the exam!");
        System.out.println("Great job! You scored in the top range.");
    } else if (score >= 50) {
        System.out.println("You passed the exam!");
    } else {
        System.out.println("Unfortunately, you did not pass. Try again next time.");
    }
}
java if-statement logical-operators
1个回答
0
投票

你已经很接近了,但是你错过了第二个条件的打印语句:

// Asking the user to input their score
System.out.print("Enter your score: ");
int score = inputDevice.nextInt();

// Single if statement using logical AND (&&) operator
if (score >= 80 && score >= 50) {
    System.out.println("You passed the exam!");
    System.out.println("Great job! You scored in the top range.");
} else if (score >= 50) {  // implicit: score < 80 for this case
    System.out.println("You passed the exam!");
    // only change is next line
    System.out.println("Good effort, but there's room for improvement.");
} else {
    System.out.println("Unfortunately, you did not pass. Try again next time.");
}
© www.soinside.com 2019 - 2024. All rights reserved.