巧用while(true){ }死迴圈的一個小例子
阿新 • • 發佈:2019-01-25
package cn.itcast.zuoye_GuanQia2_day03;
/*
* 請按如下要求編寫程式,列印選單:
1.從鍵盤上錄入一個1到5的數字;
2.當數字為1時列印選單”新建”;
當數字為2時列印選單”開啟檔案”;
當數字為3時列印選單”儲存”;
當數字為4時列印選單”重新整理”;
當數字為5時列印選單”退出”,並退出程式;
退出程式程式碼: System.exit(0);
1.從鍵盤上錄入一個1-5的數; 2.使用switch語句判斷錄入的數字為哪個選單編號,並列印對應的選單名稱; 3.使用while迴圈,重複執行1,2兩個步驟; while(true){}
*/
import java.util.Scanner;
public class Test4_switch {
public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (true) { //巧用while(true){}死迴圈 System.out.println("請輸入一個1-5的整數:"); int num = sc.nextInt(); switch (num) { case 1: System.out.println("新建"); break; case 2: System.out.println("開啟檔案"); break; case 3: System.out.println("儲存"); break; case 4: System.out.println("重新整理"); break; case 5: System.out.println("退出"); System.exit(0); break; default: System.out.println("輸入錯誤,請重新輸入"); System.out.println("================="); break; } } }
}