使用if

时间:2019-09-19 17:01:02

标签: java if-statement int java.util.scanner

所以我很困惑括号中的内容,代码可以正常工作,但我不理解吗?

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);    
    int a = scanner.nextInt(); 
    int b = scanner.nextInt();
    int c = scanner.nextInt();
    if(b < a) {
      a = b; //This part is confusing to me
    }
    if(c < a) {
      c = a; 
    }    
    System.out.println("Smallest number is " + a);
}

2 个答案:

答案 0 :(得分:2)

a被用于两个目的:

  1. 它正在存储第一个输入。
  2. 如果该新值较小,则将使用新值(从其他变量获取其值)更新该新值。

如果我正在编写程序,则不会将这两个职责都指定给a,但这就是这里发生的情况。

答案 1 :(得分:0)

我略微修改了逻辑,但您可以对案件应用相同的方法。

For a, b, and c.

If a > b
   a = b; // now a < b
otherwise leave a alone.
  1. 此时,a总是小于b
if a > c
   a = c // now a < c
otherwise, leave a alone.
  1. 此时,a始终小于c。

由于1.和2。a小于bc