为什么main方法调用compare()方法两次?

Pra*_*ra 1 java if-statement

这是代码,

public class Solution {
public static void main(String[] args) {
    compare(5);
}

public static void compare(int a) {
    if(a==5)
        System.out.println("The number is equal to 5");
    if(a<5)
        System.out.println("The number is less than 5");
    else
        System.out.println("The number is greater than 5");
}
}
Run Code Online (Sandbox Code Playgroud)

这是输出,

The number is equal to 5
The number is greater than 5
Run Code Online (Sandbox Code Playgroud)

我刚刚调用了compare方法一次,为什么它执行两次?

Mur*_*göz 10

因为你有两个if-statements没有任何关系.这就是它aa==5和检查参数两次的原因a<5.

您可以通过使用else if语句扩展第二个if来修复它.