2014-12-24 168 views
0

我正在尝试异常处理程序来计算以厘米为单位的高度。循环逻辑中的循环孔

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发生时,程序进入一个无限循环。我的逻辑中有什么错?我应该做些什么改变?

+0

什么是输入?可能你在控制台上输入double或string – Adem

回答

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); 
+0

catch中的scanner.nextLine()有什么作用?为什么第二次catch中不需要它? – Leo

+0

@Leo scanner.nextInt()只读取一行的一部分。现在,如果输入的不是整数,并调用nextInt,则会得到InputMismatchException。在这种情况下,在尝试再次读取整数之前,您必须删除包含无效输入的行。这就是scanner.nextLine()所做的。现在我看到了可能抛出的其他异常,看起来您在第二个catch块中也需要它。否则,当你输入一个负整数时,你会遇到同样的问题。 – Eran