The first stage: JAVA Quick Start (Forty-eighth lesson: JAVA_if-else double-selection structure)

grammar structure:

if(布尔表达式){

 //语句块1

}else{

      // 语句块2

}

      When the Boolean expression is true, execute statement block 1, otherwise, the statement block 2. That is, the else. Flow chart shown in Figure 3-3.

1.png

3-3 if-else double-selection structure flowchart of FIG.

[Example 3-2] if-else structure

public class Test2 {

    public static void main(String[] args) {

        //随机产生一个[0.0, 4.0)区间的半径,并根据半径求圆的面积和周长

        double r = 4 * Math.random();

       //Math.pow(r, 2)求半径r的平方

        double area = Math.PI * Math.pow(r, 2);

        double circle = 2 * Math.PI * r;

        System.out.println("半径为: " + r);

        System.out.println("面积为: " + area);

        System.out.println("周长为: " + circle);

        //如果面积>=周长,则输出"面积大于等于周长",否则,输出周长大于面积

        if(area >= circle) {

            System.out.println("面积大于等于周长");

        } else {

            System.out.println("周长大于面积");

        }

    }

}

running result:

 

FIG 3-4 FIG running effect Example 3-2

public class Test3 {
    public static void main(String[] args) {
        int a=2; 
        int b=3;
        if (a<b) {
            System.out.println(a);
        } else {
            System.out.println(b);
        }
    }
}

      The conditional operator may sometimes be used instead if-else, as shown in Example 3-3 and Example 3-4.

[Example 3-3] using if-else

 

FIG 3-5 FIG running effect Example 3-3

[Example 3-4] using the conditional operator

public class Test4 {

    public static void main(String[] args) {

        int a=2;

        int b=3;

        System.out.println((a<b)?a:b);

    }

}

 

Example 3-4 3-6 run renderings

Published 49 original articles · won praise 6 · views 10000 +

Guess you like

Origin blog.csdn.net/ZGL_cyy/article/details/104091910