为什么我的代码在查找它们之间的最大数量时同时打印 if 和 else 语句,并且如果我放置 >b?

0 java conditional-statements

我试图找到两个输入之间的最大数量,我使用的条件是:

  1. if (a>b) :a 大于 b
  2. if(a==b) :两者相等
  3. 否则:b 大于 a

现在,如果我取 a = 10 且 b = 20,我得到:b 大于 a,这是正确的。

然而,当我取 a = 30 和 b = 5 时,我得到这样的语句:a 大于 b,b 大于 a,这意味着 if(a>b) 和 else{} 的语句都是正在打印。

当我在 Google 上搜索时,他们将 if(a>=b) 写为第一个表达式。现在我的问题是,“=”对按照我们想要的方式执行有什么影响,为什么只添加“>”我就能执行这两个语句?

这是代码

import java.util.*;

public class conditional {

    public static void main(String[] args)
    {

     Scanner sc = new Scanner(System.in);
     System.out.print("Enter first number : ");
     int a = sc.nextInt();
     System.out.print("Enter second number : ");
     int b = sc.nextInt();

     if(a>b)
     {
      System.out.println("the greatest number is " + a);
     }
     if(a==b)
     {
      System.out.println("both are equal numbers");
     }
     else{
      System.out.println("the greatest number is " + b);
     }
}
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Jon*_*eet 6

您的if (a > b)陈述与以下陈述完全分开。这是演示这一点的一种方法,在两者之间添加更多代码:

if (a > b) {
    System.out.println("the greatest number is " + a);
}

System.out.println("Note how unrelated the code before and after is...");

if (a == b) {
    System.out.println("both are equal numbers");
} else {
    System.out.println("the greatest number is " + b);
}
Run Code Online (Sandbox Code Playgroud)

您的条件列表将更清楚地写为:

  • if (a>b) :a 大于 b
  • 否则, if(a==b) :两者相等
  • 否则,b 大于 a

这清楚地表明您实际上需要中间有一个“else if”:

if (a > b) {
    System.out.println("the greatest number is " + a);
} else if (a == b) {
    System.out.println("both are equal numbers");
} else {
    System.out.println("the greatest number is " + b);
}
Run Code Online (Sandbox Code Playgroud)

此时,三个分支彼此紧密相连 - 您不能将额外的语句放在“else if”之前(但在第一个“if”块之外),因为“else if”连接到第一个“if” ”。