You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Java中如何验证二维数组整数值并检测负整数抛出异常

问题原因
  • 二维数组int[][]的一级索引取到的是int[]类型的子数组,只有两级索引[i][j]才能定位到单个int元素
  • 你代码里if(myArray[1] < 0 )中的myArray[1]是子数组,无法直接和int类型的0比较,触发类型不匹配报错
  • 额外逻辑错误:你写死了一级索引为固定值1,只会判断第二个子数组,无法遍历整个二维数组
修正后的实现代码

基础for循环版本(对应你原有写法修改)

int [][] myArray = {
        {2,-2,2,2},
        {3,3,3,3}};

for(int i = 0; i < myArray.length; i++){
    for(int j = 0; j < myArray[i].length; j++){
        // 用两级索引取单个元素判断
        if(myArray[i][j] < 0 ){
            throw new IllegalArgumentException("Negative integer.");
        }
    }
}

简化增强for循环版本(避免索引写错问题)

int [][] myArray = {
        {2,-2,2,2},
        {3,3,3,3}};

for (int[] row : myArray) {
    for (int num : row) {
        if (num < 0) {
            throw new IllegalArgumentException("Negative integer.");
        }
    }
}
拓展:非正整数校验逻辑

如果你需要校验所有小于等于0的非正整数,只需要把判断条件改为num <= 0即可。

内容的提问来源于stack exchange,提问作者McBraunie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:45:05