Java Learning (5), condition structure, and java learning condition Structure
1. if... else statement
1 // use runtime 2 import java to import the package. util. optional; 3 public class IfDemo {4 public static void main (String [] args) {5 bytes input = new bytes (System. in); 6 System. out. println ("Enter the number of days off"); 7 int holiday = input. nextInt (); // obtain the integer input by the keyboard. next represents the string nextDouble represents the double type 8 if (holiday> 6) 9 {10 System. out. println ("go to Hainan"); 11} 12 else if (holiday> 3) 13 {14 System. out. println (""); 15} 16 else17 {18 System. out. println ("at home"); 19} 20} 21}View Code
Ii. switch
1 import java. util. callback; 2 public class SwitchDemo {3 public static void main (String [] args) 4 {5 callback input = new callback (System. in); 6 System. out. println ("enter a number from 1 to 5"); 7 int number = input. nextInt (); 8 switch (number) 9 {10 case 1: System. out. println ("1"); break; 11 case 2: System. out. println ("2"); break; 12 case 3: System. out. println ("3"); break; 13 case 4: System. out. println ("4"); break; 14 case 5: System. out. println ("5"); break; 15 default: System. out. println ("Error"); break; 16} 17} 18}View Code
Summary
1. constants after case cannot be repeated
2. The break can be omitted. Once omitted, the program continues to run until the break or switch ends.
3. The order of case can be reversed, and default can be placed at any position, usually at the end, which can be omitted
4. switc is used to match constants. The matching types include byte, short, int, char, String (jdk1.7 and above), and enum (jdk1.5)
5. Comparison between switch and multiple if... else statements
Switch is suitable for equivalent judgment, and is not suitable for range judgment. The syntax for equivalent judgment is more concise and intuitive.
Multi-if statement functions are more comprehensive than switch Functions