循环漏洞的逻辑

时间:2014-12-24 12:55:43

标签: java exception-handling do-while

我正在尝试一个关于异常处理的程序来计算以厘米为单位的高度。

import java.util.*;
class Ex{
private static double height(int feet, int inches) throws Exception{
        if(feet < 0 || inches < 0)
            throw new Exception("Please enter positive values only.");
        return (feet * 30.48) + (inches * 2.54);
    }

 public static void main(String args[]){
 Scanner scanner=new Scanner(System.in);
 boolean continueLoop = true;

 do{
     try
     {
         System.out.println("Enter height in feet:");
         int feet=scanner.nextInt();
         System.out.println("and in inches:");
         int inches = scanner.nextInt();
         double result = height(feet,inches);
         System.out.println("Result:"+result+" cm");
         continueLoop = false;
     }
     catch(InputMismatchException e){
         System.out.println("You must enter integers. Please try again.");
     }
     catch(Exception e){
         System.out.println(e.getMessage());
     }
 }while(continueLoop);
}
}

当发生InputMismatchException时,程序进入无限循环。我的逻辑在这里有什么错?我应该做些什么改变?

1 个答案:

答案 0 :(得分:2)

您应该将scanner.nextLine()添加到catch块中,以便使用当前行的其余部分,以便nextInt可以尝试从下一行读取新输入。

 do{
     try
     {
         System.out.println("Enter height in feet:");
         int feet=scanner.nextInt();
         System.out.println("and in inches:");
         int inches = scanner.nextInt();
         double result = height(feet,inches);
         System.out.println("Result:"+result+" cm");
         continueLoop = false;
     }
     catch(InputMismatchException e){
         System.out.println("You must enter integers. Please try again.");
         scanner.nextLine();
     }
     catch(Exception e){
         System.out.println(e.getMessage());
         scanner.nextLine();
     }
 }while(continueLoop);