条件 if 和 else

huangapple go评论48阅读模式
英文:

conditional if and else

问题

两个结果的原因是代码中使用了单独的 if 和 else 语句。第一个 if 语句检查 a 是否大于 b,输出"a 较大的数是 = 33",然后第二个 if 语句检查 a 是否等于 b,但它不满足条件。最后的 else 语句不是与第一个 if 相关联的,而是独立执行,因此总是输出"b 较大的数是 = 7"。

这是因为第二个 if 语句并不与第一个 if 相关联,而是独立的条件判断,因此无论第一个 if 是否成立,else 语句都会执行。
英文:

INPUT:

     import java.util.*;

     public class Main{ 
     public static void main(String args[]) {
     int a=33;
     int b=7;
     
     if (a>b)
        {System.out.println("the bigger no. is a = " + a); }

     if (a==b)
        {System.out.println("Both the no. are equal ");}

     else
        {System.out.println("the bigger no. is b = " + b);}


 }

}

OUTPUT:

the bigger no. is a = 33
the bigger no. is b = 7

QUESTION: Why are two results are coming, a is bigger than b so why the output is both if and else statements

I tried other scenarios but changing the values of a and b but the output is always the same

答案1

得分: 2

这是因为您没有正确使用if else语句。您编写的代码首先会检查a>b,因为条件成立,它会打印出第一个输出。然后,您在示例中调用另一个if语句,它为假,所以不会打印任何内容,然而,else语句只与第二个if语句相关联,因此在您期望第一个输出时也会打印第二个输出。正确的实现应该是:

import java.util.*;

public class Main{ 
    public static void main(String args[]) {
        int a = 33;
        int b = 7;

        if (a > b) {
            System.out.println("the bigger no. is a = " + a);
        } else if (a == b) {
            System.out.println("Both the no. are equal");
        } else {
            System.out.println("the bigger no. is b = " + b);
        }
    }
}

添加else if将形成一系列"if else"语句,以便您不会得到意外的结果!

英文:

This is happening because you are not using the if else statements correctly. The code that you have written will first check if a>b and since it is it will print out the first output. You then call another if statement in your example it is false so it does not print anything out, however, the else statement is only connected to the second if statement and therefore will also print out the second statement when you were expecting the first. The correct implementation would be

import java.util.*;

     public class Main{ 
     public static void main(String args[]) {
     int a=33;
     int b=7;
     
     if (a>b)
        {System.out.println("the bigger no. is a = " + a); }

     else if (a==b)
        {System.out.println("Both the no. are equal ");}

     else
        {System.out.println("the bigger no. is b = " + b);}

 }

}

Adding else if will add that chain of "if else" statements so you are not getting unexpected results!

huangapple
  • 本文由 发表于 2023年2月16日 12:51:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467981.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定