This question already has answers here:
Printing out a linked list using toString
                                
                                    (5个答案)
                                
                        
                                4年前关闭。
            
                    
首先,如果我做错了什么,我要道歉,因为这是我的第一篇文章,并且我对Java缺乏经验。我想知道如何打印出名为“ addressBook”的LinkedList,而不会弹出类似“ Friend @ 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");
        }
    }
}

最佳答案

对于循环:只需将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);

关于java - 如何在链接列表中打印对象? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29617489/

10-11 23:22
查看更多