第二章java中的if else语句


java中的if else语句用于测试某些条件。它评估条件为trueor false

if 语句分为三种类型。

  1. If statement
  2. If else statement
  3. If else if ladder statement

简单的 If 语句

if(condition)
{
      // If condition is true, this block will be executed
}

例如:

public class IfMain {

 public static void main(String[] args)
 {
    int price=20;
    if(price > 10)
         System.out.println("Price is greater than 10");
  }
}

输出:

输出:

价格大于 10
您可以在 if 之后编写单行后跟半色,或者您可以使用花括号编写代码块。

您可以在 if 之后编写单行后跟半色,或者您可以使用花括号编写代码块。

您可以重写上面的代码,如下所示。

public class IfMain {

    public static void main(String[] args)
    {
        int price=20;
        if(price > 10)
        {
                      System.out.println("Price is greater than 10");
                }
    }
}

if else 语句

if(condition)
{
       // If condition is true, this block will be executed
}
else
{
       // If condition is false, this block will be executed
}

例如: 检查数字是奇数还是偶数。

package org.arpit.java2blog;

public class IfElseMain {

    public static void main(String[] args)
    {
        IfElseMain ieMain=new IfElseMain();
        ieMain.checkOddOrEven(20);
    }

    public void checkOddOrEven(int number)
    {
            if(number%2==0)
            {
                         System.out.println(number+" is even");
            }
            else
            {
                     System.out.println(number+" is odd");
            }
    }
}

输出:

20 is even

if else if 阶梯语句

在我们了解 If else if 梯形语句之前,让我们先看看一些条件运算符。

条件运算符

Java 提供了许多条件运算符。其中一些是:

  • == : 检查两个变量是否相等
  • != : 检查两个变量是否不相等
  • < :检查第一个变量是否小于其他变量
  • <= :检查第一个变量是否小于或等于其他变量
  • > : 检查第一个变量是否大于其他变量
  • >= :检查第一个变量是否大于或等于其他变量
  • && : And 操作用于检查与 && 运算符一起使用的两个条件是否为真
  • || : or 操作用于检查条件之一,与 || 一起使用 运算符,为真
if(condition1)
{
     // If condition1 is true, this block will be executed.
}
else if(condition2)
{
     // If condition2 is true, this block will be executed.
}
else if(condition3)
{
     // If condition3 is true, this block will be executed.
}
else 
{ 
      // If all above conditions are false, this block will be executed. 
}

例如:

package org.arpit.java2blog;

public class IfElseIfLadderMain {

    public static void main(String[] args)
    {
        int age=28;
        if(age >= 18 && age <= 25) { 
            System.out.println("Age is between 18 and 25"); 
        } 
        else if(age >= 26 && age <= 35) { 
            System.out.println("Age is between 26 and 35"); 
        } 
        else if(age >= 36 && age <= 60){
            System.out.println("Age is between 35 and 60");
        }
        else{
            System.out.println("Age is greater than 60");
        }
    }
}

输出:

Age is between 26 and 35

这就是java中的if else语句。


原文链接:https://codingdict.com/