java - 自定义异常捕获并将不正确的值返回到终端
问题描述
使用此代码,我的目标是在终端中显示一个可以分配“等级”的 ID 号码数组。创建它以便它可以处理异常并在发生这种情况时显示一条消息。在代码的最终输出中,必须列出数组中的所有五个变量,超过“100”的变量被列为“0”。问题是,每当引发此异常时,文本都不会输出到终端,并且它会将所有其余的“等级”设置为“0”。我想知道是否有任何方法可以避免这种情况并获取代码以在“for”循环期间将消息输出到终端,以及避免用“0”替换所有其他值这是代码:
//ScoreException.Java
public class ScoreException extends Exception {
public ScoreException(String s) {
super(s);
}
}
//TestScore.Java
import java.util.*;
public class TestScore {
public static void main(String args[]) throws Exception {
Scanner input = new Scanner(System.in);
int[] ids = {1234, 2345, 3456, 4567, 5678};
int[] scores = {0, 0, 0, 0, 0};
String scoreString = new String();
final int HIGHLIMIT = 100;
String inString, outString = "";
for (int x = 0; x < ids.length; ++x) {
try{
System.out.println("Enter score for student id number: " + ids[x]);
inString = input.next();
if(scores[x]>HIGHLIMIT){
throw new ScoreException("Score over 100");
}
}catch(ScoreException e){
scores[x]=0;
System.out.println("Score over 100");
}
}
for (int x = 0; x < ids.length; ++x)
outString = outString + "ID #" + ids[x] + " Score " + scores[x] + "\n";
System.out.println(outString);
}
}
解决方案
你的异常永远不会被抛出。没有为scores
数组的任何元素分配任何内容,因此它们保持为 0。因此该表达式scores[x]==HIGHLIMIT
永远不会为真。也不应该scores[x] > HIGHLIMIT
吗?
推荐阅读
- python - 使用 python 在类中创建 Turtle 对象
- oracle - Oracle Apex 项目 ID (XXX) 不是当前页面上定义的项目
- javascript - 如何使用数组 A 的值作为键来处理 javascript 中的多维数组 B?
- azure - 我无法在 azure 中访问我的应用程序设置
- postgresql - 作为 FROM 的一部分,为 postgres 中的完整搜索提供 tsvector
- python - Python,正则表达式从字符串中提取仅使用数字而不是字母
- url - 通过 URL 运行自动化脚本
- javascript - TypeError:无法读取 null 的属性“dbName”
- scala - 如何知道 typeSignature 属性中的类型是否是指扩展某个类的任何类?
- python - 无法显示使用 python 在 GUI 中输入的所有信息