所以我是这个编程的初学者,我正在为练习做一个基本的联系人管理器。我有完美的添加接触方法,我只是想弄清楚如何使它如果在某个点之后我的数组中没有值。它不会打印那条线。基本上试图在数组中最后一个已知对象之后停止循环。我的代码就是。
public static void viewAllContacts(){
for (x = 0; x < 100; x++){
System.out.println("Full name: " +name[x]);
System.out.println("Number: " +number[x]);
System.out.println("E-mail Address: " +email[x]);
System.out.println("Home Address: " +address[x]);
System.out.println("Birthday: " +birthday[x]);
System.out.println("Nickname: " +nickname[x]);
System.out.println(" "); //space so that way the contact list is a bit prettier
}
}
答案 0 :(得分:2)
假设每个数组中的值是同步的(相同数量的元素),那么只需
for (x = 0; x < 100; x++){
if (name[x] == null)
break;
当然你也可以使用field
来保存最大数量的元素,然后只循环直到这个数字。
for (x = 0; x < maxNumberOfElements; x++){
答案 1 :(得分:1)
你应该做两件事:
第一个是创建一个类来保存所有信息,而不是将它保存在单独的数组中 - 每个属性跟踪一个数组真的很麻烦。
Person.java:
public class Person {
// Attributes
private String name;
private String number;
private String email;
private String address;
private String birthday;
private String nickname;
// Constructor
public Person(String name, String number, String email, String address,
String birthday, String nickname) {
this.name = name;
this.number = number;
this.email = email;
this.address = address;
this.birthday = birthday;
this.nickname = nickname;
}
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
// And so on for all attributes
}
然后,您应该将Person
个对象存储在ArrayList
中,以便列表的大小与您拥有的Person
个对象的数量相匹配。然后,您可以使用foreach循环迭代列表:
ArrayList<Person> persons = new ArrayList<>();
persons.add(new Person("John Doe", "555-12345", "john@doe.com", "Fake Street 999",
"1970-01-01", "Johnny"));
persons.add(new Person("Jane Doe", "555-12345", "jane@doe.com", "Fake Street 999",
"1999-12-12", "Janey"));
for(Person person : persons) {
System.out.println("Full name: " + person.getName());
System.out.println("Number: " + person.getNumber());
System.out.println("E-mail Address: " + person.getEmail());
System.out.println("Home Address: " + person.getAddress());
System.out.println("Birthday: " + person.getBirthday());
System.out.println("Nickname: " + person.getNickname());
System.out.println(); // Empty line
}
答案 2 :(得分:0)
作为补充答案,如果continue
而不是中断,您还可以null
。
如果数组中的元素没有指向任何东西以及之后的某些元素,请指向值,这可能很有用:
for (x = 0; x < 100; x++){
if (name[x] == null)
continue;
}