在這個程序中,我得到了ArrayList的錯誤輸出。 在第一行中,它總是水平地打印ArrayList的每個單獨元素。 然後它將正確地打印ArrayList。 有人可以看看代碼,看看我做錯了什麼嗎?我會告訴你兩個班。Java ArrayList輸出錯誤
第1類:
public class contactDriver
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println ("What would you like to do?");
int answer;
System.out.println ("Press 1 to add a contact.");
System.out.println ("Press 2 to display all contacts.");
answer = scan.nextInt();
ArrayList<Contact> contacts = new ArrayList<Contact>();
contacts.add(new Contact("Patrick McGee", "334-555-8860", "[email protected]"));
contacts.add(new Contact("John Appleseed", "142-555-6740", "[email protected]"));
contacts.add(new Contact("Matt Jordan", "213-555-2323", "[email protected]"));
contacts.add(new Contact("Kanye East", "255-434-9909", "[email protected]"));
contacts.add(new Contact("Derrick Flower", "144-555-1111", "[email protected]"));
if (answer == 1){
System.out.println ("Please enter the first and last name of the contact.");
String name = scan.next();
scan.nextLine();
System.out.println ("Please enter the phone number of the contact.");
String num = scan.next();
scan.nextLine();
System.out.println ("Please enter the email of the contact.");
String email = scan.next();
scan.nextLine();
contacts.add(new Contact(name, num, email));
}
if (answer == 2){
}
System.out.println(contacts);
for(Contact c : contacts) {
System.out.println(c);
二級:
public class Contact
{
public Contact(String name, String num, String email)
{
this.name = name;
this.num = num;
this.email = email;
}
public String getFirstname()
{
return name;
}
public String getNum()
{
return num;
}
public String getEmail()
{
return email;
}
public String toString()
{
return "Contact[" + name + ", " + num + ", " + email + "]";
}
private String name;
private String num;
private String email;
}
輸出:
[聯繫[帕特里克麥基,334-555-8860,[email protected] ],聯繫人[John Appleseed,142-555-6740,[email protected]],聯繫人[Matt Jordan,213-555-2323,[email protected]],聯繫人[Kanye East,255-434-9909,keast123 @ gmail.com],Conta ct [Derrick Flower,144-555-1111,[email protected]]
(全部在一行中)。
然後打印:
聯繫[帕特里克·麥基,334-555-8860,[email protected]]
聯繫[約翰蘋果核戰,142-555-6740,[email protected]] ..等等。
修復的任何想法?
謝謝:)
您的預期產量是多少? – Masudul
預計什麼? – D3X