在无限循环中抛出异常。无法找到出路。

时间:2013-10-19 22:37:29

标签: java

当抛出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);
 }

}

2 个答案:

答案 0 :(得分:4)

InputMismatchException发生时,来自Scanner的无效输入会通过while循环发回,并且该过程会重复 ad infinitum 。调用nextLine以使用Scanner中的非数字输入。这将防止未使用的数据被发送回循环

System.out.println("This is not a number " + in.nextLine());

答案 1 :(得分:-1)

由于两个原因,捕获循环内部通常是一种反模式。

  1. 你偶尔会遇到这样奇怪的行为,而且......
  2. 与自己明确检查数据相比,例外情况
  3. 所以你在这里得到了什么:

    do { 
      try {
    
      } catch () {
      }
    } while ()
    

    写得更常见......

    try {
      do {
    
      } while ();
    } catch () {
    
    }
    

    对于特殊情况,应保存例外情况;您可能不应该将它们用作每次调用方法时都会发生的功能。