所以,根據輸入的響應,我的程序打印輸出You must enter either C or F or Y or N
時出現問題。我曾嘗試在程序中放置其他if-else語句,但它無法正確運行並打破for循環。在輸入錯誤字符時嵌套另一個Java If/Else語句以打印輸出
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
// Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
// Response String
String response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("You entered no. Bye.");
}
else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact.");
//case1
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is " + standardCompact + " per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is " + couponCompact + " per day.");
}
}
else if (response.equals("F")) {
System.out.println("You have selected Full-Size. ");
//case 2
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is " + standardFullSize + " per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is " + couponFullSize + " per day.");
}
}
}
}
}
你熟悉'else'嗎? –
說實話不是真的,我仍然在學習java,而且在這裏很漂亮。到目前爲止,我知道如果,否則,如果,其他指的默認是否正確? – user3236101
你只需要添加'else'子句給你的兩個條件。在第一個條件中,你檢查'N'然後檢查'Y',那麼如果他們輸入'Z'呢?聽起來你需要一個'else'。在第二個條件中,你檢查'C'然後檢查'F',以及如果他們輸入了'X'?另一個地方'else'可以使用。這有幫助嗎? –