JAVA流程控制

1、if型(if……else……型         if……else if……型)

if(条件表达式){

语句

}

public class IfTest{
    public static void main(String [] args){
        int a = (int) (math.random()*5);    //定义int型随机变量
        int b = (int) (math.random()*5);
        if(a>b){                                        //当a>b时
            System.out.println(a);
            }
        else if(a<b){                                //当a<b时
            System.out.println(a);
            }
        else{
            System.out.println("a=b");
            }
    }
}

   2、switch型

switch(){

case 常量:

  语句;

  break;

case 常量:

  语句;

  break;

case 常量:

  语句;

  break;

default;

  语句;

}

public class SwitchTest{
    public static void main(String [] args){
        int i = (int)(math.random()*3);                    //定义随机int型0~3的变量
        switch(i){
            case 1:                                                    //当i值为1时
                System.out.println("一个和尚挑水喝");
                break;
            case 2:                                                    //当i值为2时
                System.out.println("两个和尚抬水喝");
                break;
            case 3:                                                    //当i值为3时
                System.out.println("三个和尚没水喝");
                break;
            default:                                                    //当i值为其他时
                System.out.println("这里没和尚");
            }
    }
}

  3、for型

for(){

}

public class ForTest{
    public static void main(String [] args){
        int i ;                            //定义int型变量
        int j ;                            //
        for(i = 1;i <= 9;i++){
            for(j = 1;j <=i;j++){
                System.out.print(i+"*"+j+"="+i*j+"  ");
                }
            System.out.print("
");        //换行
            }
        }
}

  4、while型

while(){

}

or

do{

}

while();

public class WhileTest{
    public static void main(String [] args){
        int i =1;
        while(i<=9){
            int j = 1;
            while(j<=i){
                System.out.print(i+"*"+j+"="+i*j+"  ");
                j++;
                }
            System.out.print("
");
            i++;
            }
        }
    }

  

原文地址:https://www.cnblogs.com/-maji/p/7010860.html