Android开发中如何判断字符串是否存在于数组及获取索引?indexOf方法失效排查
问题分析与修复方案
先直接点出你遇到的核心问题:Java的原生数组(比如String[])并没有indexOf()方法,你看到的这个方法其实是List集合或者String类的成员方法,直接在数组上调用它肯定会失效(甚至编译器会报错)。另外还有一个容易忽略的小坑,也可能导致匹配失败,我一起帮你梳理清楚:
失效原因拆解
数组没有
indexOf()方法
Java里的数组是最基础的数据结构,并没有内置indexOf()方法来查找元素索引。只有像ArrayList这类集合类,或者String类(用来查找子串位置)才有这个方法。你直接在creative_subjects数组上调用indexOf(),这本身就是语法错误。潜在的字符串匹配误差
看你的creative_subjects数组,里面的"film studies "末尾多了一个空格!如果用户输入的是正常的"film studies"(没有末尾空格),哪怕转成小写,也会和数组里的元素不匹配,导致找不到索引。
正确实现方式
下面给你两种实用的解决方案,根据你的需求选就行:
方案一:用Arrays工具类转List后查找
借助Java提供的Arrays工具类,把数组转换成List,然后用List的indexOf()方法来查找索引,代码简洁:
import java.util.Arrays; // ... 你的其他代码逻辑 // 先处理输入:去除前后空格+转小写,避免匹配误差 final String subject = ((EditText)findViewById(R.id.subject)).getText().toString().trim().toLowerCase(); // 修正数组里的空格问题,把"film studies "改成"film studies" final String creative_subjects[] ={"art and design","fine art", "dance","design and technology", "design and textiles","fashion and textiles", "film studies","music","performing arts", "photography", "physical education","graphics"}; // 数组转List后调用indexOf int index = Arrays.asList(creative_subjects).indexOf(subject); // 判断结果:index != -1 表示找到对应元素 if (index != -1) { // 这里写找到元素后的逻辑,比如拿到索引index做后续处理 System.out.println("找到元素,索引为:" + index); } else { // 未找到的处理逻辑 System.out.println("未找到该科目"); }
方案二:手动遍历数组(更灵活)
如果需要自定义匹配规则(比如允许部分字符差异、忽略中间空格),手动遍历数组会更灵活,也能避免Arrays.asList()的一些限制(比如返回的List是固定大小的):
final String subject = ((EditText)findViewById(R.id.subject)).getText().toString().trim().toLowerCase(); final String creative_subjects[] ={"art and design","fine art", "dance","design and technology", "design and textiles","fashion and textiles", "film studies","music","performing arts", "photography", "physical education","graphics"}; int foundIndex = -1; // 遍历数组查找匹配元素 for (int i = 0; i < creative_subjects.length; i++) { // 把数组元素也做去空格+转小写处理,确保匹配准确 if (creative_subjects[i].trim().toLowerCase().equals(subject)) { foundIndex = i; break; // 找到后立即退出循环,提升效率 } } // 根据结果处理 if (foundIndex != -1) { System.out.println("找到科目,索引:" + foundIndex); } else { System.out.println("未找到该科目"); }
内容的提问来源于stack exchange,提问作者john_smith
相关产品推荐
相关产品推荐

