首先,如果我做错了,我想道歉,因为这是我的第一篇文章,而且我对Java非常缺乏经验。我想知道如何打印这个名为" addressBook"的LinkedList。没有这样的东西,"朋友@ 8410b1",弹出它的位置。另外,如何循环使用if语句?
import java.io.*;
import java.util.*;
public class ABook
{
public static void main (String args[])
{
LinkedList addressBook = new LinkedList();
Scanner input = new Scanner(System.in);
System.out.println("Would you like to add a friend? (Say Y or N)");
String reply = input.nextLine();
if(reply.equals("Y"))
{
System.out.println("What is the name of your friend?");
String name = input.nextLine();
System.out.println("What is the age of your friend?");
int age = input.nextInt();
Friend newFriend = new Friend(name,age);
addressBook.add(newFriend);
System.out.println("This is your Address Book so far: " + addressBook);
}
else if(reply.equals("N")){
System.out.println("Thank you for your time");
}
}
}
答案 0 :(得分:0)
对于循环:只需将if语句替换为:
while((reply = input.nextLine()).equals("Y"))
用于打印:
覆盖toString()
中的Friend
并以此方式打印:
System.out.println("This is your address...");
addressBook.forEach(f -> System.out.println(f));
这打印整个无序的东西。如果您希望以与addressBook
中相同的顺序打印,请改用forEachOrdered(lambda)
。而不是覆盖toString()
,你也可以实现这种方法:
class Friend{
public void print(){
System.out.println("name: " + name + ...);
}
}
以这种方式打印:
System.out.println("Addressbook...");
addressBook.forEach(f -> Friend::print);