Java校验ArrayList元素时出现cannot convert int to String报错如何解决
问题原因和修复方案
报错根因
- 你定义的
receiversearch是String类型,但List.indexOf()方法返回的是元素所在位置的int类型下标,直接把int值赋值给String变量就会触发「cannot convert int to String」的类型转换错误 - 除此之外你的代码还存在多处逻辑问题:
phonebook.indexOf(phonebook)写法错误,indexOf的入参应该是要查找的Contact对象,而不是phonebook集合本身,这么写永远返回-1- 遍历过程中每次不匹配就打印「Contact not found」,会导致只要第一个元素不匹配就打印错误信息,哪怕后面存在匹配的元素
contains判断不需要显式写==true,方法本身返回的就是布尔值
修复代码示例
如果你需要拿到匹配联系人的下标,建议单独定义int变量存储下标,参考写法如下:
System.out.println("Enter receiver's name: "); String receiversearch = input.nextLine(); // 初始值设为-1代表未找到匹配联系人 int matchIndex = -1; for (int i = 0; i < phonebook.size(); i++) { Contact contactmain = phonebook.get(i); if (contactmain.getfname().contains(receiversearch)) { matchIndex = i; // 找到后直接跳出循环,不需要继续遍历 break; } } // 遍历结束后统一判断结果 if (matchIndex != -1) { System.out.println("找到匹配联系人,位置下标为:" + matchIndex); // 后续可直接通过phonebook.get(matchIndex)拿到对应联系人对象处理业务 } else { System.out.println("Contact not found"); }
如果偏好使用增强for循环,可额外加计数变量实现:
System.out.println("Enter receiver's name: "); String receiversearch = input.nextLine(); int matchIndex = -1; int index = 0; for(Contact contactmain:phonebook) { if(contactmain.getfname().contains(receiversearch)){ matchIndex = index; break; } index++; } if (matchIndex != -1) { // 处理匹配到的业务逻辑 } else { System.out.println("Contact not found"); }
额外说明
- 如果不需要获取下标,仅需要判断是否存在匹配的联系人,直接定义布尔变量做标记即可,无需存储下标
- 如果允许多个匹配结果,可以用List存储所有匹配的下标或者联系人对象,不需要找到第一个就break
内容的提问来源于stack exchange,提问作者Bradley Rose
相关产品推荐
相关产品推荐

