首页 > 解决方案 > Java 中的异常处理 - 继续执行,直到用户输入四个有效的员工 ID

问题描述

这段代码有什么问题:

DebugTwelve4.java:25: 错误: 找不到符号 throw(new FixDebugEmployeeIDException("Number too high" + emps[x])); ^ 符号:类 FixDebugEmployeeIDException 位置:类 DebugTwelve4 DebugTwelve4.java:36:错误:找不到符号 catch(FixDebugEmployeeIDException 错误) ^ 符号:类 FixDebugEmployeeIDException 位置:类 DebugTwelve4 2 个错误 错误:找不到或加载主类 DebugTwelve4

DebugEmployeeIDException.java:

public class DebugEmployeeIDException extends Exception
{
   public DebugEmployeeIDException()
   {
      super("Debug employee exception");
   }
}

-----------------------------------------------------------
DebugTwelve4.java:

// An employee ID can't be more than 999
// Keep executing until user enters four valid employee IDs
// This program throws a FixDebugEmployeeIDException
import java.util.*;
public class DebugTwelve4
{
   public static void main(String[] args)
   {
      Scanner input = new Scanner(System.in);
      String inStr, outString = "";
      final int MAX = 999;
      int[] emps = new int[4];
      int x;
      try
      {
      for(x = 0; x < emps.length; ++x)
      {
        System.out.println("Enter employee ID number");
         inStr = input.next();
         throw(new NumberFormatException("Number format exception"));
         {
            emps[x] = Integer.parseInt(inStr);
            if(emps[x] > MAX)
            {
               throw(new FixDebugEmployeeIDException("Number too high " + emps[x]));
            }
         }
      }
         
      }
      catch(NumberFormatException error)
         {  
            --x;
            System.out.println(inStr + "\nNonnumeric ID");
         }
         catch(FixDebugEmployeeIDException error)
         {  
        --x;
        System.out.println("FixDebugEmployeeIDException");
         }

      for(x = 0; x < emps.length; ++x);
      {
         outString = outString + emps[x] + " ";
      }
      System.out.println("Four valid IDS are: " + outString);    
   }
}

标签: javaexception

解决方案


由于您在一个方法(主要方法)中编写所有代码,因此实际上不需要抛出任何异常。

通常,当您链接方法调用并且您不想在那里处理错误然后->您将其抛出并将其传播回调用者以供调用者处理时,您会抛出异常。

在您的问题的上下文中,您可以在循环中进行简单的 if/else 检查,以确保输入永远不会超过 999。

int[] employeeIds = new int[4]
final int _MAX_ = 999;

for (int i = 0 ; i < employeeIds.length; i++) {
  int input = sc.nextInt();
  if (input > _MAX_) {
    System.out.println("Invalid ID, please try again!");
    i--; // when invalid input, this ensures that the index stays the same
    continue;
  } else {
    employeeIds[i] = input;
  }
}

// loop through employeeIds and print your output

推荐阅读