Java學習 (五)、條件結構,java學習條件結構
一、if...else語句

![]()
1 //導入包使用Scanner
2 import java.util.Scanner;
3 public class IfDemo{
4 public static void main(String [] args){
5 Scanner input=new Scanner(System.in);
6 System.out.println("請輸入假期天數");
7 int holiday=input.nextInt();//獲取鍵盤輸入的整數 next表示字符串 nextDouble表示double類型
8 if(holiday>6)
9 {
10 System.out.println("去海南");
11 }
12 else if(holiday>3)
13 {
14 System.out.println("去海邊");
15 }
16 else
17 {
18 System.out.println("在家");
19 }
20 }
21 }
View Code
二、switch

![]()
1 import java.util.Scanner;
2 public class SwitchDemo{
3 public static void main(String []args)
4 {
5 Scanner input=new Scanner(System.in);
6 System.out.println("請輸入1-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
小結
1.case後面的常量不能重復
2.break可以省略,一旦省略,程序就會一直往下執行,直到遇見break或switch結束
3.case的順序可以顛倒,default可以放在任何位置,一般放在最後,可以省略
4.switc用於匹配常量,能匹配的類型有byte,short,int,char,String(jdk1.7及以上),enum(jdk1.5)
5.switch和多重if...else語句比較
switch適合做等值判斷,不適合做區間判斷,做等值判斷的時候語法更簡潔,直觀
多重if語句功能比switch更全面