2013-02-26 83 views
1

//在下面的程序中,初始時當用戶遇到指令時,他可以簡單地輸入標記以退出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!"); 
    } 
} 

回答

2

用戶輸入999打破循環後,您沒有做任何事情時,其999如下,

intInput2 = Integer.parseInt(userInput); 

if (intInput2 == 999) { 
break; 
} 
3

您使用兩個不同的變量,intInputintInput2。我不明白你爲什麼需要第二個(就在catch塊之前)。只需重用intInput,這是您在while循環中針對哨兵值進行檢查的人。

+0

以前的答案已經奏效,但爲了補充您的答案,我已經嘗試過發佈前,事情是哨兵價值工作,但有一個問題,計算沒有,只要我按下一個鍵繼續對於年齡大於12歲,小於64歲,大於64歲的人來說,該計劃每次增加6美元到產出,而不是增加8美元或11美元 – user2109589 2013-02-26 11:43:00