当 InputMismatchException 被抛出时,我进入了一个无限循环,我终生无法弄清楚原因。基本上,该程序的主要目标是为用户输入的负数抛出异常,并确保用户实际输入了一个整数(而不是“r45”之类的东西)。任何帮助将不胜感激。谢谢你。
import java.util.*;
public class conversion{
static Scanner in = new Scanner (System.in);
static final double centimeters_per_inch = 2.54;
static final int inches_per_foot = 12;
public static void main (String [] args){
int feet;
int inches;
int totalInches;
double centimeters;
boolean done = false;
do{
try
{
System.out.print("Enter feet: ");
System.out.flush();
feet = in.nextInt();
System.out.println();
System.out.print("Enter inches: ");
System.out.flush();
inches = in.nextInt();
if (feet < 0 || inches < 0)
throw new NonNegative();
System.out.println();
done = true;
System.out.println("The numbers you entered are " + feet +" feet and " + inches+ " inches");
totalInches = inches_per_foot * feet + inches;
System.out.println();
System.out.println("The total number of inches = " + totalInches);
centimeters = totalInches * centimeters_per_inch;
System.out.println("The number of centimeteres = " + centimeters);
}
catch (NonNegative a){
System.out.println(a.toString());
}
catch(InputMismatchException e) {
System.out.println("This is not a number");
}
}while(!done);
}
}