Java入门之选择结构

1、顺序结构

Java的基本结构是顺序结构,按照代码顺序一句一句执行。

2、选择结构

(1)if单选择结构

 1 public static void main(String[] args) {
 2         Scanner scanner = new Scanner(System.in);
 3         System.out.println("input:");
 4         String str = scanner.nextLine();
 5         //if单选择结构
 6         if(str.equals("Nana")){
 7             System.out.println("Congratulations!" + str);
 8         }
 9 
10         scanner.close();
11     }

 

(2)if双选择结构

 1 public static void main(String[] args) {
 2         Scanner scanner = new Scanner(System.in);
 3         System.out.println("input:");
 4         String str = scanner.nextLine();
 5        
 6         if(str.equals("Nana")){
 7             System.out.println("Congratulations!" + str);
 8         }else{
 9              System.out.println("Sorry!" + str);
10          }
11 
12         scanner.close();
13     }

 

(3)if多选择结构

 1     public static void main(String[] args) {
 2         Scanner scanner = new Scanner(System.in);
 3         System.out.println("input:");
 4         String str = scanner.nextLine();
 5         
 6         if(str.equals("Nana")){
 7             System.out.println("Congratulations!" + str);
 8         }else if(str.equals("Jane")){
 9             System.out.println("Congratulations!" + str);
10         }else if(str.equals("Lee")){
11             System.out.println("Congratulations!" + str);
12         }else{
13             System.out.println("Sorry!" + str);
14         }
15         
16         scanner.close();
17     }

 

(4)嵌套的if结构

 1 {
 2     public static void main(String[] args) {
 3         Scanner scanner = new Scanner(System.in);
 4         System.out.println("input:");
 5         String str = scanner.nextLine();
 6         
 7         if(str.equals("Nana")){
 8             int age = scanner.nextInt();
 9             if(age == 18){
10                 System.out.println("Congratulations! " + age + "\'s " + str);
11             }
12         }
13 
14         scanner.close();
15     }
16 }

 

(5)switch多选择结构

 1 {
 2     public static void main(String[] args) {
 3         Scanner scanner = new Scanner(System.in);
 4         System.out.println("input:");
 5         String str = scanner.nextLine();
 6        
 7         switch (str){  
 8             case "Nana":
 9                 System.out.println("I\'m 18 years old.");
10                 break;
11             case "Lee":
12                 System.out.println("I\'m 14 years old.");
13                 break;
14             default:
15                 System.out.println("sorry!");
16         }
17 
18         scanner.close();
19     }
20 }

switch变量类型可以是: byte,short,int,char,String(JDK7开始支持)

没有添加break,会有switch穿透问题,但具体要看业务需要。

 

posted @ 2022-07-11 11:10  嗒嗒媛  阅读(37)  评论(0编辑  收藏  举报