java - 在java中不断出现错误“无法将int转换为String”
问题描述
我正在尝试检查用户输入值是否存在于 an 中ArrayList
,但我一直收到此错误。
无法将 int 转换为 String
这是我的代码:
System.out.println("Enter receiver's name: ");
String receiversearch=input.nextLine();
for(Contact contactmain:phonebook) {
if(contactmain.getfname().contains(receiversearch)==true){
receiversearch=phonebook.indexOf(phonebook);
}
else {
System.out.println("Contact not found");
}
}
解决方案
这是您的代码的重写,也许它可以帮助您
System.out.println("Enter receiver's name: ");
String receiversearch=input.nextLine();
Contact foundContact = null; // here we will store the found contact (if any)
for(Contact contactmain:phonebook) {
if (contactmain.getfname().contains(receiversearch)) { // == true is redundant, contains(..) returns a boolean
//receiversearch=phonebook.indexOf(phonebook); //this is wrong and not needed, you can remove this line. Your phonebook items are Contact objects and not String so you cannot assign them to String. Moreover indexOf(phonebook) is wrong, you are trying to get the index of a List instead of an item on the List
foundContact = contactmain; //contact is found assign it to foundContact
break; //break the for loop since we found what we were looking for
}
}
if (foundContact != null) {
System.out.println("Contact has been found!"); // foundContact is not null which means that we have found it
} else {
System.out.println("Contact not found"); // foundContact is null which means that we couldn't find it
}
推荐阅读
- selenium - Selenium 为 wait.until 抛出空指针
- postgresql - 关于 AWS EC2 安装中的 PLPYTHONU 和请求模块
- sql - 如何在 SQL 选择语句中列出城市的不同名称?
- apache-spark - 如何避免读取处于待处理状态的镶木地板文件?
- sql - 如何解决这个 SQL 查询挑战?
- javascript - How to concatenate relative path or generate unique identifier svg contained in nested folders?
- node.js - Puppteer image styling off using heroku
- grep - 有什么方法可以强制 grep 理解 Windows 行尾?
- google-sheets - 连接字符串所需的 Google 表格功能
- java - 如何将 int numStudents 复制到 Integer i?