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

如何从嵌套数组获取值/索引并做条件判断,及单独输出指定元素

处理Java嵌套数组的取值、索引判断与单独显示

嘿,我来给你捋清楚这个Java二维数组的操作方法哈!你给出的嵌套数组是:

String[][] kstemmers = new String[][] { {"John", "Mary"}, {"Alice", "Bob"} };

这是个典型的二维字符串数组,外层包含2个一维数组,每个一维数组又有2个字符串元素。下面分场景给你说怎么操作:

一、获取值/索引并做条件判断

1. 直接通过索引定位取值+判断

如果你知道元素的位置,直接用外层索引[内层索引]就能拿到值,接着就能做条件判断。比如:

// 拿到第一个数组里的Mary,判断是否等于目标值
if (kstemmers[0][1].equals("Mary")) {
    System.out.println("找到了目标元素Mary!");
}

要是想找某个元素的具体索引位置,就用嵌套循环遍历查找:

// 查找Bob的索引位置
for (int outerIndex = 0; outerIndex < kstemmers.length; outerIndex++) {
    for (int innerIndex = 0; innerIndex < kstemmers[outerIndex].length; innerIndex++) {
        if (kstemmers[outerIndex][innerIndex].equals("Bob")) {
            System.out.println("Bob的外层索引是" + outerIndex + ",内层索引是" + innerIndex);
        }
    }
}

2. 遍历数组批量做条件判断

如果不知道元素位置,就用增强for循环(或者普通for循环)遍历所有元素,同时做条件筛选。比如找出所有以"A"开头的名字:

for (String[] innerArray : kstemmers) {
    for (String name : innerArray) {
        if (name.startsWith("A")) {
            System.out.println("找到以A开头的名字:" + name);
        }
    }
}

二、单独显示John、Mary、Alice、Bob这些值

1. 直接通过索引逐个输出

适合元素数量少、位置明确的情况,直接定位每个元素输出:

System.out.println(kstemmers[0][0]); // 输出John
System.out.println(kstemmers[0][1]); // 输出Mary
System.out.println(kstemmers[1][0]); // 输出Alice
System.out.println(kstemmers[1][1]); // 输出Bob

2. 遍历输出所有元素

如果数组元素多,不想逐个写索引,用嵌套循环一次性输出所有元素:

for (String[] innerArray : kstemmers) {
    for (String name : innerArray) {
        System.out.println(name);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:48:57