Java 环中的环孔';s逻辑

Java 环中的环孔';s逻辑,java,exception-handling,do-while,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

我正在尝试一个异常处理程序,以厘米为单位计算高度

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);
}
}
import java.util.*;
前级{
私有静态双高(整数英尺,整数英寸)抛出异常{
如果(英尺<0 | |英寸<0)
抛出新异常(“请仅输入正值”);
返回(英尺*30.48)+(英寸*2.54);
}
公共静态void main(字符串参数[]){
扫描仪=新的扫描仪(System.in);
布尔连续运算=真;
做{
尝试
{
System.out.println(“以英尺为单位输入高度:”;
int feet=scanner.nextInt();
System.out.println(“和英寸:”);
int inches=scanner.nextInt();
双倍结果=高度(英尺,英寸);
System.out.println(“结果:+Result+cm”);
continueLoop=false;
}
捕获(输入不匹配异常e){
System.out.println(“您必须输入整数,请重试”);
}
捕获(例外e){
System.out.println(e.getMessage());
}
}while(continueLoop);
}
}

当发生输入不匹配异常时,程序进入无限循环。我的逻辑有什么错误?我应该做什么更改?

您应该向catch块添加
scanner.nextLine()
,以便使用当前行的其余部分,以便
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);

什么是输入?很可能您正在控制台上输入double或string catch中scanner.nextLine()有什么用?为什么在第二个catch中不需要它?@Leo scanner.nextLine()只读取一行的一部分。现在,如果您输入的不是整数的东西,并调用nextInt,您将得到InputMismatchException。在这种情况下,在再次尝试读取整数之前,必须先删除包含无效输入的行。scanner.nextLine()就是这么做的。现在我看到了您可能抛出的其他异常,看起来您在第二个catch块中也需要它。否则,当输入负整数时,将遇到相同的问题。