-1

我必须确保包含处理异常的语句,但是当我这样做时,变量 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;
}
4

1 回答 1

4

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

    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
   }
}
于 2012-11-18T04:30:47.227 回答