首页 > 解决方案 > 在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");
    }
}

标签: java

解决方案


这是您的代码的重写,也许它可以帮助您

    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
    }

推荐阅读