我想了解这里的错误。我试图声明一个String变量,其中包含另一个类的name属性,如下所示:
public static void findContact() {
int se = 1;
String nom;
String nomS;
Contact ce;
while (se == 1) {
nom = JOptionPane.showInputDialog("Name of desired contact: ");
int i;
for (i = 0; i <= it; i++) {
ce = c[i];
nomS = ce.getName();//here is the error
if (nomS.equalsIgnoreCase(nom)) {
System.out.println(c[i]);
}
}
se = Integer.parseInt(JOptionPane.showInputDialog("Would you like to search for another contact [1]Y [2]N"));
}
}
c,联系人列表像这样声明为常量[我将省略不必要的代码]:
private static final Contact c[] = new Contact[100];
并这样声明了通讯录类[我将显示相关部分]:
public class Contact {
private String name;
private int phone;
private String mail;
public Contact() {
name = " ";
phone = 0;
mail = " ";
}
public Contacto(String name, int phone, String mail) {
this.name = name;
this.phone = phone;
this.mail = mail;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name + phone + mail;
}
我尝试在方法内部创建另一个Contact类型变量:
Contact ce = new Contact();
或
Contact ce = new Contact("",1,"");
无济于事。最糟糕的部分是代码实际编译并显示了它应该显示的内容,它确实比较并显示了联系人,就好像它工作得很好一样,但是我仍然明白了这一点[我的变量在实际代码中是西班牙语]: Java console result
首先感谢您的阅读和帮助。
编辑:我有一个数组填充方法:
public static void addContact() {
String nom;
int phone;
String mail;
int se = 1;
while (se == 1 ) {
nom = JOptionPane.showInputDialog("Name of contact: ");
phone = Integer.parseInt(JOptionPane.showInputDialog("Phone number: "));
mail = JOptionPane.showInputDialog("contact's mail");
System.out.println(nom + " " + phone + " " + mail);
Contact con = new Contact(nom, phone, mail);
c[it] = con;
System.out.println(c[0]);
it++;
se = Integer.parseInt(JOptionPane.showInputDialog("Add another contact 1Y 2N"));
}
}
因此,在任何给定时刻,数组至少填充1个。