变量不变

时间:2012-11-18 04:28:16

标签: java exception

我必须确保包含处理异常的语句,但是当我这样做时,变量Amount不会改变。帮助

public static void main(String[] args){
    AmwayTickets run = new AmwayTickets();
    System.out.print(run.ticketAmount());
}

public int ticketAmount(){
    System.out.println("Enter the amount of tickets you wish to purchase: ");
    int amount = 0;
    try {
        amount = keyboard.nextInt();
    }
    catch (InputMismatchException e){
        System.out.println("Invalid Amount");
        ticketAmount();
        return amount;
    }
    if (amount < 0){
        System.out.println("Invalid Amount");
        ticketAmount();
        return amount;
    }   
    return amount;
}

1 个答案:

答案 0 :(得分:4)

你确定你应该使用递归来解决这个问题吗?即使你应该这样做,你的递归调用也是错误的,因为你没有在返回金额之前将返回的值赋值给amount变量。即,

    amount = ticketAmount(); // note the difference
    return amount;

或更简单地说:

    return ticketAmount();

但我建议你不要这样做。如果这是我的代码,我会使用简单的while循环。

boolean amountCorrect = false;
while (!amountCorrect) {
   try {
      // try to get an assign amount
      // if successful, assign amountCorrect = true; on the next line
   } catch (InputMismatchException e) {
      // give error warning here
   }
}