如果用户输入了无效的代码,则显示“您选择了无效的选项,并将价格设置为0”。
import java.util.Scanner;
public class ShadyRestRoom {
public static void main(String[]args) {
Scanner scanner= new Scanner(System.in);
int QueenBed = 125;
int KingBed = 139;
int KingPullout = 165;
System.out.println("Choose: 1 for a Queen bed Choose: 2 for a King bed or Choose: 3 for a King bed with a pullout couch");
int RoomChoice= scanner.nextInt();
if (RoomChoice == 1)
System.out.println("$125 for a Queen bed");
if (RoomChoice == 2)
System.out.println("$139 for a King bed");
if (RoomChoice == 3)
System.out.println("$165 for a King bed with a pullout couch");
while (RoomChoice == 4)
System.out.println("ERROR Please enter a valid Choice");
RoomChoice = scanner.nextInt();
if (RoomChoice == 8)
System.out.println("ERROR Please enter a valid Choice");
RoomChoice = scanner.nextInt();
}
}
我似乎不知道如何设置它,所以它=( 如果用户输入的代码无效,则显示“您选择了无效的选项,并将价格设置为0。)
答案 0 :(得分:1)
完成选择的一种方法是switch语句。它是为此做的。因此,选择需要进行切换。
现在,对于每个有效的选择,您都有一个“ case”语句。此外,最后,对于未明确提及的所有其他内容,都有一个“默认值”。
您可以使用默认值“ cheat”,并将变量重置为您选择的定义值。
现在,这又使循环中的条件变得更加简单,因为它不再那么模糊(“除了..以外,还有些输入”),但是只有一个定义的值表示“另一个循环”。
我以“ -1”作为指标,表示“出了点问题”。但是您可以将任何有意义的信息用作“转义符”(这就是所谓的值:-1是“转义码”)。因此,while会检查我的转义符“ -1”,并继续询问,直到用户给出范围内的内容为止。
public static class ShadyRestRoom {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int QueenBed = 125;
int KingBed = 139;
int KingPullout = 165;
int RoomChoice = -1;
do {
System.out.println("Choose: 1 for a Queen bed Choose: 2 for a King bed or Choose: 3 for a King bed with a pullout couch");
RoomChoice = scanner.nextInt();
switch (RoomChoice) {
case 1:
System.out.println("$125 for a Queen bed");
break;
case 2:
System.out.println("$139 for a King bed");
break;
case 3:
System.out.println("$165 for a King bed with a pullout couch");
break;
//you can also explicitely take a group of numbers that need to be treated the same way:
case 4:
case 8:
default: //this is the default for everything that wasn't metioned before
RoomChoice = -1;
System.out.println("ERROR Please enter a valid Choice");
}
} while (-1 == RoomChoice);
}
}
顺便说一句:约定使用小写字母表示变量。因此,以“ roomChoice”代替“ RoomChoice”会更好。这样,您可以立即看到它是一个变量而不是类。