我想解決這個問題,而不使用arraylist。 我想將聯繫人添加到字符串數組中的特定索引。然後以逗號分隔字符串格式顯示所有添加的聯繫人。 我的代碼只給出了最後一個添加合同的結果: 聯繫人[first = Bob,last = Moore,number = 555-9756] 問題在哪裏? 有什麼想法如何解決???在java中的字符串數組
這個類包含的主要方法:
這是主要的類:
public class ExampleApp {
public static void main(String[] args) {
PhoneBook pb = new PhoneBook("Personal book");
System.out.println(pb.getName());
pb.add("Alice", "Green", "555-1234");
pb.add("Mary", "Smith", "555-6784");
pb.add("Bob", "Moore", "555-9756");
System.out.println(pb.toString());// here i want to display all the contracts seperated by commas
System.out.println(pb.first());// first contract
System.out.println(pb.get(2));// second contract
String toBeFound = new String("Moore");
System.out.println(pb.find(toBeFound));// display the found contract
}
}
這是電話簿類:
public class PhoneBook {
public static final int MAX = 10;
public String name;
String[] contracts = new String[MAX]; // i created an array of strings
Contact c;
/**
* Create a new phonebook with given name
*/
public PhoneBook(String name) {
this.name = name;
}
/**
* Return the phonebook name
*/
public String getName() {
return name;
}
/**
* Insert a new contact at the end
*/
public void add(String first, String last, String number){
c=new Contact(first,last,number);
for(int i=0;i<MAX;i++){ // i added for each array index the contracts strings
contracts[i]= c.toString();
}
}
/**
* Return the first contact
*/
public String first() {
return get(1);
}
/**
* Return the i-th contact (supposing that first
* index is 1)
*/
public String get(int i) {
String s =contracts[i].toString();
return s;
}
/**
* Return a string containing the list of textual
* representation of all contacts, separated by ", ".
* List starts with "("and ends with ")"
*/
public String toString() {
String s= " ";
for(int i=1;i<MAX;i++){ // here i tried to display the string looping the array
s=contracts[i].toString();
}
return s;
}
/**
* Return the textual representation of first
* contact containing "needle"
*/
public String find(String needle) {
//TODO: to be implemented
return null;
}
}
這是接觸類:
public class Contact {
public String first;
public String last;
public String number;
public String[] contacts;
public Contact(String first, String last, String number) {
this.first=first;
this.last = last;
this.number=number;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@Override
public String toString() {
return "Contact [first=" + first + ", last=" + last + ", number="
+ number + "]";
}
}
感謝您的答案,但在這裏我試圖解決不使用arraylist – Niranjan 2014-11-02 11:40:45
for(int i = 0; i
2014-11-02 11:54:03
@Niranjan你的add方法和toString方法是錯誤的 – 2014-11-02 12:00:56