提问人:Begichh 提问时间:5/28/2022 最后编辑:dani-vtaBegichh 更新时间:5/28/2022 访问量:33
不能更改 Java 对象中方法的变量
Cant change method's variables in Java objects
问:
我在更改联系人对象中的变量值时遇到了问题。我正在尝试制作联系人列表,但我无法更改变量的值。我有调用 changeName 方法的 editContact 方法,这两个方法都传递了 ArrayList 对象 trought 引用,因此在 main 方法中更改值 trought ArrayList 应该不会有问题,但问题是当我想更改对象的名称时,它不会更改它。我在这里遗漏了什么吗?
package telefonski_imenik;
public class Contact {
protected String name;
protected String lastname;
protected String number;
public Contact(String name, String lastname, String number) {
setName(name);
setLastName(lastname);
setNumber(number);
}
public void setName(String name) {
this.name = name;
}
public void setLastName(String lastname) {
this.lastname = lastname;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return this.name;
}
public String getLastName() {
return this.lastname;
}
public String getNumber() {
return this.number;
}
}
package telefonski_imenik;
import java.util.ArrayList;
import java.util.Scanner;
public class TelefonskiImenik {
public static void createContact(String ime, String prezime, String broj, ArrayList<Contact>
ContactList) {
Contact noviKontakt = new Contact(ime, prezime, broj);
ContactList.add(noviKontakt);
}
public static void editContact(ArrayList<Contact> ContactList) {
System.out.println("Unesite nove podatke");
changeName(ContactList);
}
public static void changeName(ArrayList<Contact> ContactList) {
Scanner novinput = new Scanner(System.in);
System.out.println("Unesite staro ime");
String oldName = novinput.nextLine();
System.out.println("Unesite novo ime");
String newName = novinput.nextLine();
for (int i = 0; i < ContactList.size(); i++) {
if (ContactList.get(i).equals(oldName)) {
ContactList.get(i).setName(newName);
}
}
novinput.close();
}
public static void main(String[] args) {
ArrayList<Contact> ContactList = new ArrayList<Contact>();
Scanner input = new Scanner(System.in);
System.out.println("Unesite podatke");
String name = input.nextLine();
String lastname = input.nextLine();
String number= input.nextLine();
createContact(name, lastname, number, ContactList);
for (int i = 0; i < ContactList.size(); i++) {
System.out.println(ContactList.get(i).getName());
System.out.println(ContactList.get(i).getLastName());
System.out.println(ContactList.get(i).getNumber());
}
editContact(ContactList);
for (int i = 0; i < ContactList.size(); i++) {
System.out.println(ContactList.get(i).getName());
System.out.println(ContactList.get(i).getLastName());
System.out.println(ContactList.get(i).getNumber());
}
input.close();
}
}
答:
1赞
Boris Ivanov
5/28/2022
#1
您忘记获取循环中对象的名称:
for (int i = 0; i < ContactList.size(); i++) {
if (ContactList.get(i).equals(oldName)) {
ContactList.get(i).setName(newName);
}
}
ContactList.get(i).getName().equals(oldName)
评论
0赞
Begichh
5/28/2022
非常感谢,在此之前我一直在使用 ContactList.get(i).name == oldName,但在此之前它无法工作,感谢您的回答,它帮助了我!
评论