【问题标题】:How to print object within a linked list? [duplicate]如何在链表中打印对象? [复制]
【发布时间】:2015-04-14 00:59:08
【问题描述】:

首先,如果我做错了什么,我想道歉,因为这是我的第一篇文章,我对 Java 非常缺乏经验。我想知道如何在不弹出类似“Friend@8410b1”之类的内容的情况下打印这个名为“addressBook”的 LinkedList。另外,我怎样才能循环这个 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");
        }
    }
}

【问题讨论】:

标签: java object linked-list


【解决方案1】:

对于循环:只需将 if 语句替换为:

while((reply = input.nextLine()).equals("Y"))

对于打印: 在Friend 中覆盖toString() 并以这种方式打印:

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);

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2022-01-06
    • 2014-01-03
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 2011-09-27
    • 1970-01-01
    相关资源
    最近更新 更多