尝试在while循环中捕获Block

时间:2015-08-06 03:14:52

标签: java loops try-catch

我如何使用try / catch块,以便用户可以在程序中的错误处开始?

while (true) {
    try {
        System.out.println("Enter your amount paid ");      
        int payCheck = s.nextInt(); 
        System.out.println("Amount Paid: $" +payCheck);

        System.out.println("Enter your expenses");
        int expenses = s.nextInt();  
        System.out.println("Expenses: $" +expenses);

        System.out.println("Enter your tax percentage taken off as a decimal:");
        float taxRate = s.nextFloat();  
        System.out.println("Tax Rate" +taxRate);

        double totalPay =  (double) Math.round(payCheck - expenses)* taxRate ;  
        DecimalFormat f = new DecimalFormat("##.00");
        System.out.println( "Total Pay: $" +f.format(totalPay));
    } catch (Exception e) {
        System.out.println("Please enter a number");
    }
}

2 个答案:

答案 0 :(得分:1)

Try-Catch无法正常工作。使用类似的东西:

int input = -1;
while (input < 0) {
    try { 
        input = s.nextInt();
        if (input < 0) {
            System.out.println("Invalid input. Please enter an positive integer.");
        }
    } catch (Exception e) {
        System.out.println("Invalid input. Please enter an positive integer.");
    }
}

每次让用户输入。

答案 1 :(得分:1)

使用如下函数:

int readInt(Scanner s) {
   int result = 0;
   boolean isNumber = false;
   while(!isNumber) {
      try {
         result = s.nextInt();
         isNumber = true; 
      } catch (Exception e) {
        System.out.println("Please enter a number");
      }
   }
   return result;
}

使用如下:

while (true) {
    System.out.println("Enter your amount paid ");      
    int payCheck = readInt(s); 
    System.out.println("Amount Paid: $" +payCheck);

    System.out.println("Enter your expenses");
    int expenses = readInt(s);  
    System.out.println("Expenses: $" +expenses);

    System.out.println("Enter your tax percentage taken off as a decimal:");
    float taxRate = s.nextFloat(); //Here you must write a function readFloat  
    System.out.println("Tax Rate" +taxRate);

    double totalPay =  (double) Math.round(payCheck - expenses)* taxRate ;  
    DecimalFormat f = new DecimalFormat("##.00");
    System.out.println( "Total Pay: $" +f.format(totalPay));
}