java - if 语句检查数组是否为空或空,不起作用
问题描述
我的主要任务是工作(粗略翻译):
编写一个方法,该方法返回一维整数数组中的最小数。
现在我必须做一个附带任务(粗略的翻译):
添加 if 语句,检查数组是否为 null 或为空,如果是,则返回 0。
方法:
public static int smallestNumber (int[] array1) {
int smallest = array1[0];
if (array1 == null || array1.length == -1) {
return 0;
}
else {
for (int element : array1) {
if (element < smallest) {
smallest = element;
}
}
}
return smallest;
}
主要的:
public static void main(String[] args) {
int[] tab1 = {}; //empty array?
int smallestNumber = smallestNumber(tab1);
System.out.printf("The smallest number is: %d", smallestNumber);
}
如果我只检查 null,则该方法有效。但我很困惑为什么它不能在空数组上工作。
int[] tab1 = {};
编辑:我也试过 array1.length == 0;
解决方案
首先,数组的大小为非负数,因此array1.length
不能为 -1,而是与 进行比较0
。
其次,赋值 int smallest = array1[0];
尝试访问空数组的第 0 个位置,这将导致java.lang.ArrayIndexOutOfBoundsException
.
因此,总而言之,将赋值移到smallest
else 块中,并在尝试访问任何数组值之前检查空数组或空数组的条件。
public static int smallestNumber (int[] array1) {
int smallest;
if (array1 == null || array1.length == 0) {
return 0;
}
else {
smallest = array1[0];
for (int element : array1) {
if (element < smallest) {
smallest = element;
}
}
}
return smallest;
}
推荐阅读
- operating-system - CPU 寄存器值如何更新?
- azure-active-directory - Microsoft SSO 在我的团队选项卡和任务模块中失败
- php - 在我的电子商务网站中,单个产品页面未加载
- css - 在 React 组件上测试样式
- widget - iOS14如何模糊小部件背景
- .net - IndexedDB 中的 Blazor 图像:RuntimeError:内存访问越界
- php - 如果用户关闭浏览器且受 PW 保护的页面仍然打开,则注销用户并删除 cookie
- css - 将透明导航栏放在 jumbotron 顶部 - Bootstrap
- c++ - Mosquitto:使用非静态回调函数
- stored-procedures - 如何在 DB2 for z/OS 中将 Cursor 作为 OUT 参数返回