3.1.4 switch structure
- switch(){
case:
break;
case:
break:
default:
break;
}
2. Code Example: Judging that a random letter is a vowel or consonant
/** * Test the use of switch statements * @author Wang Li Sheng * */ public class testSwitch { public static void main(String[] args){ //Testing vowels or consonants of letters char c='a'; int rand=(int)(26*Math.random()); char c2=(char)(c+rand); System.out.println("The letter is:"+c2); switch (c2){ case 'a': case 'e': case 'i': case 'o': case 'u': System.out.println("vowel"); break; case 'y': case 'w': System.out.println("Half vowel"); break; default: System.out.println("consonant"); } } }
Note: In the switch statement, variables cannot be defined after the break statement
3.2.1 Use of while
-
Structure:
-
While{
...
You have to change the conditional statement, otherwise the dead cycle
} -
Code example: Calculate the sum from 0 to 100 and:
/** * Testing the Use of While Statements * * @author Wang Li Sheng * */ public class testWhile { public static void main(String[] args){ //Calculate the value of 1+2+3+...+100 int i=1; int sum=0; while(i<=100){ sum=sum+i; i++; } System.out.println("And:"+sum); } }
3.2.2 DO-WHILE cycle
Functions are the same as while
The difference is: do-while executes the loop first, and then judges.
3.2.3 for cycle
- For (Defining initial variables; Judging conditions; Changing conditional variables){
}
Note: When defining a trial variable, if there are two variables, you only need to use an int.
Code example:
/** * Test for loop structure * * @author Wang Li Sheng * */ public class testFor { public static void main(String[] args){ //Training 1: Calculate the sum of 1 to 100 int sum=0; for(int i=1;i<=100;i++){ sum+=i; } System.out.println("sum="+sum); //Training 2: Output 90 to 1 multiples of all 3 for (int i=90;i>=1;i=i-3){ System.out.print(i+","); } //Training 3: Values of output data for i and j for (int i=1,j=i+6;i<=5;i++,j=i*2){ System.out.println("i="+i+"j="+j); } } }
Output: