我正在进行编码练习以模拟手机中的联系人列表,您可以搜索现有联系人并从系统输入添加新联系人,但是,我遇到了一些处理扫描仪的问题而且不知道原因:(I真的很感谢你的帮助,所以提前谢谢!)
这是我的代码: 首先是联系人课程:
public class Contacts {
private String contactName;
private String phoneNumber;
public Contacts(){
}
public Contacts(String contactName, String phoneNumber) {
this.contactName = contactName;
this.phoneNumber = phoneNumber;
}
public String getContactName() {
return contactName;
}
public String getPhoneNumber() {
return phoneNumber;
}
}
然后我创建了一个MobilePhone类来保存联系人ArrayList,使用addContact()和searchContactByName()方法:
public class MobilePhone {
private ArrayList<Contacts> contactList = new ArrayList<Contacts>();
//searchContactByName() method takes the contact name you want to search and
//return the contact object with that contact name if it's in the list, and return null if the contact is not on the list
public Contacts searchContactByName(String contactName){
Contacts returnContact = new Contacts();
boolean contactExist = false;
for(int i = 0; i < contactList.size(); i++){
if(contactList.get(i).getContactName() == contactName){
System.out.println("Contact " + contactName + " found");
contactExist = true;
returnContact = contactList.get(i);
break;
}
}
if(contactExist == true){
return returnContact;
}else{
System.out.println("not found");
return null;
}
}
//addContact2() method use the searchContactByName() method to make sure
//that the contact you add does not already exists in the list
public void addContact2(String contactName, String phoneNumber){
Contacts newContact = new Contacts(contactName,phoneNumber);
if(searchContactByName(contactName) != null){
System.out.println("This contact is already in the contact list.");
}else{
contactList.add(newContact);
System.out.println(contactName + " has been added to the list");
}
}
但是,在我尝试实现该功能的主要方法中:
public class TestMain {
public static Scanner myScanner = new Scanner(System.in);
public static void main(String[] args) {
MobilePhone jolenePhone = new MobilePhone();
//First add a contact object with contactName "Rish" in the list:
jolenePhone.addContact2("Rish","1234");
//Then use searchContactByName() function to search the contact object with name "Rish" in the list:
jolenePhone.searchContactByName("Rish");
}
}
但是,如果我使用扫描仪功能:
MobilePhone jolenePhone = new MobilePhone();
//First add a contact object with contactName "Rish" in the list:
jolenePhone.addContact2("Rish","1234");
System.out.println("Please enter search name: ");
String searchName = myScanner.nextLine();
jolenePhone.searchContactByName(searchName);
然后,我通过控制台输入的联系人名称“Rish”找不到searchFunction:
我不明白为什么我会直接传递contactName参数“Rish”,或者我使用scanner.nextLine()函数从控制台输入,我在这里错过了什么?< / p>
答案 0 :(得分:0)
将if(contactList.get(i).getContactName() == contactName)
改为= equals()
。
==用于引用相等,equals用于对象相等。
答案 1 :(得分:0)
请勿使用==
使用equals()
或equalsIgnoreCase()
来忽略案例敏感