[英]Better way to display information from an ArrayList using a toString and Enhanced for loop
我希望能夠使用Contact
類的ContactArrayList
顯示聯系人列表中的信息。
我有一個ContactArrayList
類,其中包含一個Contact
類對象。 在ContactArrayList
類內部,我有一個add
, remove
, size
, isEmpty
等。 對於類的方法將被用於該ContactArrayList
在ContactArrayList
類與其他方法一起。
在我的main / driver類中,我有一個ContactArrayList
類的對象,並創建了一個“用戶”對象和Contact
類的幾個“罐頭”對象。
當用戶選擇顯示所有聯系人(包括固定對象和用戶對象)的信息時,我嘗試使用帶有ContactArrayList
類的toString
方法的增強的for循環W /,但是因為我使用的是使用Contact
類的增強的for循環,迭代器”變量,當我想使用ContactArrayList
類toString
時,它會顯示並使用Contact
toString
顯示信息。
ContactArrayList
: import java.util.ArrayList;
public class ContactArrayList
{
ArrayList <Contact> contactArray = new ArrayList <Contact> ();
String toStringM = " ";
public Contact set(int index, Contact element)
{
return contactArray.set(index, element);
}
public Boolean add(Contact element)
{
return contactArray.add(element);
}
public Contact remove(int index)
{
return contactArray.remove(index);
}
public int size()
{
return contactArray.size();
}
public void clear()
{
contactArray.clear();
}
public boolean isEmpty()
{
return contactArray.isEmpty();
}
@Override
public String toString()
{
for(int i = 0; i < contactArray.size(); i++)
{
toStringM = "Displaying all contacts and information: "
+ contactArray.get(i).getName() +
contactArray.get(i).getLastName() +
contactArray.get(i).getPhoneNumber()+
contactArray.get(i).getEmailAddress();
}
return toStringM;
}
public void sort()
{
ArrayList <Contact> tempSort = new ArrayList <> ();
while(!contactArray.isEmpty())
{
int index = 0;
for (int i = 1; i < contactArray.size(); i++)
{
if(contactArray.get(i).compareTo(contactArray.get(index)) == -1)
{
index = i;
}
}
tempSort.add(contactArray.get(index));
contactArray.remove(index);
}
contactArray = tempSort;
}
public void addContact(String passedString)
{
ArrayList <Contact> addContact = new ArrayList <Contact> ();
for(Contact c : contactArray)
{
if (c.getName().indexOf(passedString) > -1)
{
addContact.add(c);
}
}
}
public void searchAndRemove (String passedString)
{
for(int i = 0; i < contactArray.size(); i++)
{
if (contactArray.get(i).getName().indexOf(passedString) > -1)
{
contactArray.remove(i);
}
}
}
}
Main
: import java.util.ArrayList;
import java.util.Scanner;
public class HomeWork10 {
public static void main(String[] args)
{
userInput();
}
public static void userInput()
{
Scanner in = new Scanner(System.in);
ContactArrayList cal1 = new ContactArrayList ();
Contact c1 = new Contact(); //User Input Object
//"Canned" refernce Objects
Contact c2 = new Contact("James", "Conney", "7608949843",
"jamesConney@seeMe.com");
Contact c3 = new Contact("JJ", "Jim", "7608939836",
"theStuff@gmail.com");
Contact c4 = new Contact("Jimmer", "ConBoy", "7608040500",
"jimConBoy@seeMe.com");
//Adding canned objects to the ArrayList
cal1.add(c2);
cal1.add(c3);
cal1.add(c4);
String name = " ";
String lastName = " ";
String phoneNumber = " ";
String emailAddress = " ";
String yesOrNo = " ";
int userInput = 0;
boolean userContinues = true;
do
{
System.out.println("Please enter 1, 2, 3, 4, or 5 for the following"
+ " options");
System.out.println("1. Add a new Contact, 2. display all contacts, "
+ "3. search for a contact and remove them,"
+ " 4. Sort the Contact LIST by name, 5. Quit: ");
userInput = in.nextInt();
in.nextLine();
switch(userInput)
{
case 1:
System.out.println("Please enter the new contact info"
+ "(Name, lastName, phoneNumber and emailAddress): ");
name = in.nextLine();
lastName = in.nextLine();
phoneNumber = in.nextLine();
emailAddress = in.nextLine();
c1 = new Contact(name, lastName, phoneNumber, emailAddress);
cal1.add(c1);
break;
case 2:
System.out.println(cal1.toString());
break;
case 3:
System.out.println("Enter a contact to search for and remove: ");
name = in.nextLine();
cal1.searchAndRemove(name);
break;
case 4:
System.out.println("Sorting the contact list by name "
+ "and displaying it to the screen.");
cal1.sort();
System.out.println(cal1.toString());
break;
case 5:
System.out.println("Goodbye");
System.exit(0);
break;
default:
System.out.println("Invalid entry, try again.");
break;
}
System.out.println("Would you like to continue ? (Y/N): ");
yesOrNo = in.next();
if(yesOrNo.equalsIgnoreCase("Y"))
{
System.out.println("");
}
else
{
System.out.println("Goodbye");
userContinues = false;
}
}while(userContinues);
}
}
Contact
: import java.util.Scanner;
public class Contact implements Comparable
{
private static String name = " ";
private static String lastName = " ";
private static String phoneNumber = " ";
private static String emailAddress = " ";
public Contact()
{
//Default constructor
}
public Contact(String passedName, String passedLastName,
String passedPhoneNumber, String passedEmailAddress)
{
this.name = passedName;
this.lastName = passedLastName;
this.phoneNumber = passedPhoneNumber;
this.emailAddress = passedEmailAddress;
}
//Setter Methods
public void setName(String passedName)
{
this.name = passedName;
}
public void setLastName(String passedLastName)
{
this.lastName = passedLastName;
}
public void setPhoneNumber(String passedPhoneNumber)
{
this.phoneNumber = passedPhoneNumber;
}
public void setEmailAddress(String passedEmailAddress)
{
this.emailAddress = passedEmailAddress;
}
//Getter Methods
public String getName()
{
return this.name;
}
public String getLastName()
{
return this.lastName;
}
public String getPhoneNumber()
{
return this.phoneNumber;
}
public String getEmailAddress()
{
return this.emailAddress;
}
//Methods
public String toString()
{
return "Name, Last name, phone number, and email in order: "
+ this.name +" " + this.lastName + " " + this.phoneNumber +
" " + this.emailAddress;
}
public int compareTo(Object other)
{
Contact passedContact = (Contact) other;
if(this.lastName.compareTo(passedContact.lastName) == 0)
{
return this.name.compareTo(passedContact.name);
}
else
{
return this.lastName.compareTo(passedContact.lastName);
}
}
public static String userInput()
{
Scanner in = new Scanner(System.in);
System.out.println("Please enter your name, last name,"
+ " phone number, and email address: ");
Contact.name = in.nextLine();
Contact.lastName = in.nextLine();
Contact.phoneNumber= in.nextLine();
Contact.emailAddress = in.nextLine();
Contact newContact = new Contact(name, lastName, phoneNumber, emailAddress);
return newContact.getName() + newContact.getLastName() +
newContact.getPhoneNumber() + newContact.getEmailAddress();
}
public boolean equals(Object anObject)
{
//equals method which trys to check if the object to be ,ade is legdible
if (anObject == null || getClass() != anObject.getClass())
{
return false ;
}
Contact otherContact = (Contact) anObject ;
return (this.name.equals(otherContact.getName())) &&
this.lastName.equals(otherContact.getLastName()) &&
this.phoneNumber.equals(otherContact.getPhoneNumber()) &&
this.emailAddress.equals(otherContact.getEmailAddress());
}
}
Please enter 1, 2, 3, 4, or 5 for the following options 1. Add a new Contact, 2. display all contacts, 3. search for a contact and remove them, 4. Sort the Contact LIST by name, 5. Quit: 1 Please enter the new contact info(Name, lastName, phoneNumber and emailAddress): Mike Dim 123456789 email Would you like to continue ? (Y/N): y Please enter 1, 2, 3, 4, or 5 for the following options 1. Add a new Contact, 2. display all contacts, 3. search for a contact and remove them, 4. Sort the Contact LIST by name, 5. Quit: 2 Name, Last name, phone number, and email in order: Mike Dim 123456789 email Name, Last name, phone number, and email in order: Mike Dim 123456789 email Name, Last name, phone number, and email in order: Mike Dim 123456789 email Name, Last name, phone number, and email in order: Mike Dim 123456789 email Would you like to continue ? (Y/N):
總的來說,我將繼續努力解決這個問題,這可能很簡單,但希望有人指出這一點。 如果您需要有關ContactArrayList類,Contact類或Main / driver類的更多信息,請告訴我!
感謝您提供缺少的課程。 問題出在您的Contact
類中:
private static String name = " ";
private static String lastName = " ";
private static String phoneNumber = " ";
private static String emailAddress = " ";
這些變量都是static
,這意味着它們對於每個Contact
都不存在一次,而對於每個Application都不存在一次。 因此,所有Contact
都將共享相同的name
, lastName
等。
如果刪除static
修飾符,則它應該起作用。
但是您的代碼中還有其他一些要解決的問題:
ContactArrayList
。 其他開發人員會查看它,並期望它擴展ArrayList
,但不會。 只需將其命名為Contacts
,那就更好了(我會在這里將其稱為表單)。 您不應使用toString
顯示用戶可讀的文本。 它旨在輸出文本以進行調試。 將您的toString
方法替換為以下內容:
Contact
:
public String toReadableString() { return "Name: " + this.name + " " + this.lastName + ", phone number: " + phoneNumber + ", email: " + this.emailAddress; }
不要調用您的ArrayList<Contact>
contactArray
。 它不是數組。 稱其為members
..
Contacts
->您的toString
方法已損壞。 您只是將每個Contact
的結果存儲在相同的toStringM
(也是一個不好的名字。我不知道這是什么意思)
public String toReadableString() { String result = "Displaying all contacts and information:"; for (Contact contact : members) { result += "\\n\\t" + contact.toReadableString(); } return result; }
addContact(String passedString)
方法已損壞。 我不知道它應該做什么,但是它只會創建一個新的ArrayList
,您將永不執行任何操作。 .indexOf(passedString) > -1
用.contains(passedString)
它可能做同樣的事情,但是更容易閱讀。 Contact
的方法public static String userInput()
應該做什么。 看來您可以擺脫它。 您對Contact extends Comparable
繼承是錯誤的。 應該是Contact extends Comparable<Contact>
您的compareTo
方法無法正常工作。 將其替換為以下內容:
@Override public int compareTo(Contact other) { if (this.lastName.compareTo(other.lastName) == 0) { return this.name.compareTo(other.name); } else { return this.lastName.compareTo(other.lastName); } }
sort
方法替換為Collections.sort(members);
(您可以這樣做,因為Contact
現在是正確的Comparable<Contact>
) toString()
方法是java的意思是產生供開發人員調試的Strings
。 我建議要么實現自己的toReadableString()
,要么簡單地定義您要如何現場渲染它。 Java 8具有一些不錯的功能:
case 2:
String s = contacts.stream()
.map(c -> Stream.of(c.getName(), c.getLastName(), c.getPhoneNumber(), c.getEmailAddress())
.collect(Collectors.joining(", ")))
.collect(Collectors.joining("\n\t", "Displaying all contacts and information:\n\t", ""));
System.out.println(s);
break;
首先,我們從contacts
創建Stream
。 然后,我們變換Stream
的Contact
s轉換為Stream
的String
s的map
。 再次,我們創建四個值的Stream
,並將它們與,
聯接。 第二個Stream
將創建每個聯系人。
然后,我們回到外部Stream
,那里現在有了可讀聯系人Stream
。 我們也將它們連接起來,用"\\n\\t"
分隔它們,從而創建一個類似於以下內容的String
:
Displaying all contacts and information:
Mike, Dim, 123456789, email
Foo, Bar, 987654321, hello@wor.ld
您已經在ArrayList的toString
方法中循環了。 所以你不應該做
cal1.toString();
代替
for(Contact display : cal1.contactArray)
{
System.out.println(display.toString());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.