if (standOrTerraceTickets != 1 && standOrTerraceTickets != 2) {
System.out.print("Invalid input. Please enter 1 for stand tickets or 2 for terrace tickets. ");
}
if (standOrTerraceTickets == 1 || standOrTerraceTickets == 2) {
System.out.print("Now, how many adult tickets do you require? ");
}
int adultTickets = aScanner.nextInt();
System.out.print("How many children's tickets do you require? ");
所以在上面的这篇文章中,当用户最初输入3(而不是1或2)时,会打印错误消息invalid input
。当他们输入1时,它会跳过此打印
Now, how many adult tickets do you require?
并直接转到儿童票上。
为什么?
答案 0 :(得分:2)
你需要改善你的条件。
这里需要的是nested if-else
。截至目前,对于任何输入,您的最后一个语句System.out.print("How many children's tickets do you require? ");
将始终运行。
int adultTickets = 0;
if (standOrTerraceTickets != 1 && standOrTerraceTickets != 2) {
System.out.print("Invalid input. Please enter 1 for stand tickets or 2 for terrace tickets. ");
}
else if (standOrTerraceTickets == 1 || standOrTerraceTickets == 2) {
System.out.print("Now, how many adult tickets do you require? ");
adultTickets = aScanner.nextInt();
System.out.print("How many children's tickets do you require? ");
}
答案 1 :(得分:1)
请使用以下开关案例构造。
switch(standOrTerraceTickets)
{
case 1:
case 2:
System.out.print("Now, how many adult tickets do you require? ");
break;
default:
System.out.print("Invalid input. Please enter 1 for stand tickets or 2 for terrace tickets. ");
break;
}
答案 2 :(得分:1)
如果输入为3,则显示错误消息 - 输入不正确时,应显示错误消息。如果输入为1或2(两个有效输入),则不会显示错误消息并输入成人票号。然后显示儿童票的提示。
while (standOrTerraceTickets != 1 && standOrTerraceTickets != 2)
{
System.out.print("Invalid input. Please enter 1 for stand tickets or 2 for terrace tickets. ");
standOrTerraceTickets = aScanner.nextInt();
}
System.out.print("Now, how many adult tickets do you require? ");
int adultTickets = aScanner.nextInt();
System.out.print("How many children's tickets do you require? ");
答案 3 :(得分:0)
只是因为输入是3而if语句仅在standOrTerraceTickets == 1 || standOrTerraceTickets == 2