java - 如何在 java 中修复“未能抛出 IllArgumentException”
问题描述
我正在尝试编写一个程序,对两个整数的列表进行排序,以便元素按升序排列,列表的大小保持不变,如果列表的大小不等于 2,则给出 IllegalArgumentException。
这就是我所拥有的:
public static void sort2(List<Integer> t) { //t is a the list
if(t.size() < 3) {
Collections.sort(t);
System.out.println(t);
}
else if (t.size() == 2) {
throw new IllegalArgumentException("List is empty");
}
}
但是,当我进行 JUnit 测试时,排序通过,但异常测试失败。测试如下:
public void test10a_sort2() {
ArrayList<Integer> t = new ArrayList<>();
String error = "lab0.sort2(t) failed to throw an IllegalArgumentException";
try {
lab0.sort2(t);
fail(error);
}
catch (IllegalArgumentException x) {
// do nothing
}
catch (Exception x) {
fail("lab0.sort2(t) threw the wrong kind of exception");
}
t.add(1);
try {
lab0.sort2(t);
fail(error);
}
catch (IllegalArgumentException x) {
// do nothing
}
catch (Exception x) {
fail("lab0.sort2(t) threw the wrong kind of exception" + x);
}
t.add(2);
t.add(3);
try {
lab0.sort2(t);
fail(error);
}
catch (IllegalArgumentException x) {
// do nothing
}
catch (Exception x) {
fail("lab0.sort2(t) threw the wrong kind of exception");
}
}
不太确定我做错了什么。我也尝试使用 try catch,但似乎效果不佳。
解决方案
if(t.size() < 3) {
// ...
}
else if (t.size() == 2) {
throw new IllegalArgumentException("List is empty");
}
只有当第一个条件为假且第二个条件为真时,您才会抛出异常,即t.size() >= 3 && t.size() == 2
. 这显然是不可能的,所以永远不会抛出异常。
把抛出异常的条件放在前面:
if (t.size() != 2) {
throw ...
}
如果大小是2之后再放东西。
推荐阅读
- xcode - 如何在 appStore 连接中更新我的应用信息?
- java - resultset.next() 仅显示第一行的输出
- azure - Azure WebJob 索引正在进行中
- pywinauto - 是否可以查看帮助文本等菜单项属性?
- php - PHP不适用于https,而是下载文件
- function - 经过三天的试验和搜索,我仍然无法让 .getValue 函数工作
- css - 每当我单击按钮时淡出图像
- python - 熊猫将两个单独的列转换为一个日期时间列?
- swift - (Xcode/Swift) 加载具有依赖项的 dylib
- java - 如何在 Flink 中增加 SinkFunction 的 numRecordsOutPut 指标?