java - 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);
}
}
解决方案
由于您在一个方法(主要方法)中编写所有代码,因此实际上不需要抛出任何异常。
通常,当您链接方法调用并且您不想在那里处理错误然后->您将其抛出并将其传播回调用者以供调用者处理时,您会抛出异常。
在您的问题的上下文中,您可以在循环中进行简单的 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
推荐阅读
- javascript - 设置节点之间的固定距离 d3-force
- reactjs - 为什么我的表格组件过滤器会使浏览器选项卡崩溃?
- android - Android Studio 4.1.1“系统 UI 没有响应”错误
- c# - 从串口读取换行符返回第一个值
- kubernetes - 升级集群时如何处理基于 kops 的 kubernetes api 的更新?
- image - SwiftUI - 按下按钮时移动和旋转图像
- javascript - 尝试从 aws lambda 运行 javascript 代码以列出或终止 ecs 任务
- node.js - 允许带有 npm 头盔的 S3 图像
- javascript - 无法删除 react-data-table-component 中的白色标题
- javascript - 如何从 JSON url 呈现列表?- ReactJS 钩子