程序控制语句

编程语言使用控制(control )语句来产生执行流,从而完成程序状态的改变,如程序顺序执行和分支执行。

if else

// Demonstrate if-else-if statements. 
class IfElse { 
    public static void main(String args[]) { 
        int month = 4; // April 
        String season; 
 
        if(month == 12 || month == 1 || month == 2) 
            season = "Winter"; 
        else if(month == 3 || month == 4 || month == 5) 
            season = "Spring"; 
        else if(month == 6 || month == 7 || month == 8) 
            season = "Summer"; 
        else if(month == 9 || month == 10 || month == 11) 
            season = "Autumn"; 
        else 
            season = "Bogus Month"; 
 
        System.out.println("April is in the " + season + "."); 
    } 
} 

switch case

// A simple example of the switch. 
class SampleSwitch { 
    public static void main(String args[]) { 
        for(int i=0; i<6; i++) 
            
        switch(i) { 
            case 0: 
                System.out.println("i is zero."); 
                break; 
            case 1: 
                System.out.println("i is one."); 
                break; 
            case 2: 
                System.out.println("i is two."); 
                break; 
            case 3: 
                System.out.println("i is three."); 
                break; 
            default: 
                System.out.println("i is greater than 3."); 
        } 
    } 
} 

while

// Demonstrate the while loop. 
class While { 
    public static void main(String args[]) { 
        int n = 10; 
 
        while(n > 0) { 
            System.out.println("tick " + n); 
            n--; 
        } 
    } 
} 

do while

// Demonstrate the do-while loop. 
class DoWhile { 
    public static void main(String args[]) { 
        int n = 10; 
 
        do { 
            System.out.println("tick " + n); 
            n--; 
        } while(n > 0); 
    } 
} 

for

// Using the comma. 
class Comma { 
    public static void main(String args[]) { 
        int a, b; 
 
        for(a=1,  b=4; a<b; a++ ,  b--) { 
            System.out.println("a = " + a); 
            System.out.println("b = " + b); 
        } 
    } 
} 

break

// Using break with nested loops. 
class BreakLoop3 { 
    public static void main(String args[]) { 
        for(int i=0; i<3; i++) { 
            System.out.print("Pass " + i + ": "); 
            for(int j=0; j<100; j++) { 
                if(j == 10) break; // terminate loop if j is 10 
                System.out.print(j + " "); 
            } 
            System.out.println(); 
        } 
        System.out.println("Loops complete."); 
    } 
} 

continue

// Demonstrate continue. 
class Continue { 
    public static void main(String args[]) { 
        for(int i=0; i<10; i++) { 
            System.out.print(i + " "); 
            if (i%2 == 0) continue; 
            System.out.println(""); 
        } 
    } 
} 

 

你可能感兴趣的:(程序控制语句)