1 import java.util.Scanner; 2 /** 3 * 4 * 功能描述: 編寫程序,使用嵌套if選擇結構,根據出行的月份和選擇的艙位輸出實際的機票價格。 5 * 6 * 7 * @Author: apple. 8 * @Date: 2019/12/3 5:15 PM 9 */ 10 public class Ticket { 11 static Scanner sc = new Scanner(System.in); 12 13 public static void main(String[] args) { 14 int month;//月份 15 int cabin;//艙位 16 double price = 5000; 17 System.out.println("請輸入您出行當月份:1~12"); 18 month = sc.nextInt(); 19 System.out.println("請問您選擇頭等艙還是經濟艙?頭等艙輸入1:經濟艙輸入2"); 20 cabin = sc.nextInt(); 21 //旺季 22 if (month >= 4 && month <= 10) { 23 if (cabin == 1) { 24 price = price * 0.9; 25 System.out.println("當前享受9折,打完折后:"+price); 26 } else if (cabin == 2) { 27 price = price * 0.6; 28 System.out.println("當前享受6折,打完折后:"+price); 29 30 } else { 31 System.out.println("error"); 32 } 33 } else if (month > 0 && month < 13) {//淡季 34 if (cabin == 1) { 35 price = price * 0.5; 36 System.out.println("當前享受5折,打完折后:"+price); 37 38 } else if (cabin == 2) { 39 price = price * 0.4; 40 System.out.println("當前享受4折,打完折后:"+price); 41 42 } 43 } else { 44 System.out.println("error"); 45 } 46 System.out.println("您當機票價格為:" + price); 47 } 48 }
思路:分為兩大if便容易讓人理解了。
結果:

