Sentinel值不会在循环中退出
问题描述:
//在下面的程序中,初始时当用户遇到指令时,他可以简单地输入标记以退出while循环,但是,当您得到您想要的票的结果时买,按999不退出程序Sentinel值不会在循环中退出
import java.io.*;
public class ManyTickets
{
public static void main (String [] args) throws IOException
{
String userInput;
String userInput2;
int intInput = 0;
int intInput2 = 0;
double total = 0.00;
BufferedReader ageInput = new BufferedReader (new InputStreamReader (System.in));
try{
System.out.println("Please enter your age, or press '999' to exit.");
userInput = ageInput.readLine();
intInput = Integer.parseInt (userInput);
while (intInput != 999)
{
if (intInput < 0 || intInput > 110)
System.out.println("Invalid entry, or your age seems a bit too high to enter buy these tickets");
else if (intInput <= 12)
{
total = total + 6;
System.out.println("The ticket cost for 1 ticket is " + total);
}
else if (intInput <= 64)
{
total = total + 11;
System.out.println("The ticket cost for 1 ticket is " + total);
}
else
{
total = total + 8;
System.out.println("The ticket cost for 1 ticket is $" + total);
}
System.out.println("So far, your tickets cost is: $" + total );
System.out.print("Would you like to buy more tickets? You can buy up to 1 more ticket per customer! If no press 999 to exit");
userInput = ageInput.readLine();
intInput2 = Integer.parseInt (userInput);
}
}catch (NumberFormatException e){
System.out.println("Please restart the program, and enter an integer instead!");
}
}
{
double total = 0.0;
System.out.println("Thank you, The total cost for the ticket is: $" + total);
System.out.println("Have a nice day!");
}
}
答
用户输入999打破循环后,您没有做任何事情时,其999如下,
intInput2 = Integer.parseInt(userInput);
if (intInput2 == 999) {
break;
}
答
您使用两个不同的变量,intInput
和intInput2
。我不明白你为什么需要第二个(就在catch块之前)。只需重用intInput
,这是您在while循环中针对哨兵值进行检查的人。
以前的答案已经奏效,但为了补充您的答案,我已经尝试过发布前,事情是哨兵价值工作,但有一个问题,计算没有,只要我按下一个键继续对于年龄大于12岁,小于64岁,大于64岁的人来说,该计划每次增加6美元到产出,而不是增加8美元或11美元 – user2109589 2013-02-26 11:43:00