天天看点

java if..else

文章目录

Java 支持数学中常见的逻辑条件:

  • 小于:a < b
  • 小于或等于:a <= b
  • 大于:a > b
  • 大于或等于:a >= b
  • 等于a == b
  • 不等于:a != b

Java 有以下条件语句:

  • 使用if指定的代码块将被执行,如果一个指定的条件是真
  • 使用else指定的代码块将被执行,如果相同的条件为假
  • 使用else if指定一个新的条件测试,如果第一个条件为假
  • 使用switch指定的代码许多替代块被执行

我们测试两个值以找出 10是否大于 8。如果条件为true,则打印一些文本:

package test8;

public class test1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        if (10 > 8) {
              System.out.println("10大于8");
            }
    }

}
      

运行:

java if..else

或者你也可以这样:

package test8;

public class test2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int x = 20;
        int y = 18;
        if (x > y) {
          System.out.println("x大于 y");
        }
    }

}
      
java if..else

在上面的示例中,我们使用两个变量x和y来测试 x 是否大于 y(使用>运算符)。由于 x 是 10,y 是 8,并且我们知道 10 大于 8,所以我们在屏幕上打印“x 大于 y”。

当if前面的语句非真的时候,我们就执行else语句。举个例子:

package test8;

public class test3 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int time = 20;
        if (time < 18) {
          System.out.println("成功.");
        } else {
          System.out.println("失败.");
        }
    }

}
      
java if..else

如果20小于18才执行if语句,因此我们只能执行else语句。

简单点说就是if语句非真,那么就执行else if,else if是并列的按顺序的,else if都为假,则执行else.

package test8;

public class test4 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int time = 22;
        if (time < 10) {
          System.out.println("川川");
        } else if (time < 20) {
          System.out.println("菜鸟.");
        } else {
          System.out.println("川川菜鸟.");
        }
        
    }

}
      
java if..else

因为前面都为假,只能执行else.

如果前面你学得比较好,那么你一定能懂这部分代码:

package test8;

public class test5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int time = 20;
        if (time < 18) {
          System.out.println("川川.");
        } else {
          System.out.println("菜鸟.");
        }
    }

}
      
java if..else

那么我们换一下新的方式来表达:

package test8;

public class test6 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int time = 20;
        String result = (time < 18) ? "川川" : "菜鸟";
        System.out.println(result);
    }

}
      
java if..else

你可以看到这里就变换成了简单的一句话。细细品味一下。