while循環中有switch,如何跳出while循環


case 5:
                System.out.println("**************積分抽獎**************");while(true) {
                    System.out.println("請選擇 1.抽獎 2.退出");
                    int choose2 = input.nextInt();
                    switch (choose2) {
                    case 1:
                        String lottery = userDao.lottery(loginAccount);
                        System.out.println(lottery);
                        break;
                    case 2:
                        break;
                    default:
                        System.out.println("輸入有誤");
                        break;
                    }
                }

switch中的break只能終止switch循環,無法終止while循環,如果將break改成return,雖然能終止循環,但是會用力過猛,將整個方法都終止,如何做到精准的終止掉當前while循環,我們可以在外面定義一個boolean變量flag來控制while循環,在case中,通過改變flag的值來控制while循環.

 1 case 5:
 2                 System.out.println("**************積分抽獎**************");
 3                 boolean flag = true;
 4                 while(flag) {
 5                     System.out.println("請選擇 1.抽獎 2.退出");
 6                     int choose2 = input.nextInt();
 7                     switch (choose2) {
 8                     case 1:
 9                         String lottery = userDao.lottery(loginAccount);
10                         System.out.println(lottery);
11                         break;
12                     case 2:
13                         flag = false;
14                         break;
15                     default:
16                         System.out.println("輸入有誤");
17                         break;
18                     }
19                 }

 


免責聲明!

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



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