switch語句小練習


java有兩鍾選擇判斷語句,分別是if else和switch case語句。

  下面我們做一個switch case語句的練習。

        // 定義一個掃描器
        Scanner sacnner = new Scanner(System.in);
        // 定義一個變量用於接收用戶輸入的月份
        int month=sacnner.nextInt();
        
        switch (month) {
        case 1:
            System.out.println(month + "月份是冬天");
            break;
        case 2:
            System.out.println(month + "月份是冬天");
            break;
        case 3:
            System.out.println(month + "月份是春天");
            break;
        case 4:
            System.out.println(month + "月份是春天");
            break;
        case 5:
            System.out.println(month + "月份是春天");
            break;
        case 6:
            System.out.println(month + "月份是夏天");
            break;
        case 7:
            System.out.println(month + "月份是夏天");
            break;
        case 8:
            System.out.println(month + "月份是夏天");
            break;
        case 9:
            System.out.println(month + "月份是秋天");
            break;
        case 10:
            System.out.println(month + "月份是秋天");
            break;
        case 11:
            System.out.println(month + "月份是秋天");
            break;
        case 12:
            System.out.println(month + "月份是冬天");
            break;
        default:
            System.out.println("不合法的輸入");

        }

但是在編程時我們要盡量簡化代碼,讓代碼更簡潔,便於觀看,在這里我們可以利用switch語句的語法合並同一季節的輸出語句

        // 定義一個掃描器
        Scanner sacnner = new Scanner(System.in);
        // 定義一個變量用於接收用戶輸入的月份
        int month=sacnner.nextInt();
        
        switch (month) {
        case 12:
        case 1:
        case 2:
            System.out.println(month + "月份是冬天");break;
        case 3:
        case 4:
        case 5:
            System.out.println(month + "月份是春天");break;
        case 6:
        case 7:
        case 8:
            System.out.println(month + "月份是夏天");break;
        case 9:
        case 10:
        case 11:
            System.out.println(month + "月份是秋天");break;
        default:
            System.out.println("不合法的輸入");

        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM