创建一个包含 Notes 类的链接列表,它基本上是一个包含 NotePages 的对象,另一个类包含“标题”和描述的字符串。 Notes 类扩展了另一个类,即前面提到的 LinkedList 类。问题是,当我尝试打印带有注释页的注释时,显示如下:
Note one
[]
指定在对象中显示的内容如下所示:
NotePages page = new NotePages("title one", "Description");
Notes note = new Notes("Note one", page);
note.printNote();
我尝试创建其他方法(例如 String 方法)来尝试正确返回页面,但无济于事。
这是我的 Notes 对象的代码。
public class Notes extends LinkedList{
private String title;
private LinkedList<NotePages> pages;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public LinkedList<NotePages> getPages() {
return pages;
}
public void setPages(LinkedList<NotePages> pages) {
this.pages= pages;
}
public Notes(String title, LinkedList<NotePages> pages) {
this.title = title;
this.pages= pages;
}
void printNote(){
System.out.println(getTitle()+"\n"+getPages());
}
}
我需要显示器输出更接近此的内容:
Note one
title one
description
这是 NotePages 类:
import java.awt.*;
public class NotePages {
private String title;
private String description;
private Color label;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Color getLabel() {
return label;
}
public void setLabel(Color label) {
this.label = label;
}
NotePages(String title, String description, Color label){
this.title = title;
this.description = description;
this.label = label;
}
NotePages(String title,String description){
this.title = title;
this.description = description;
}
void printPage(){
System.out.println(getTitle() + "\n "+ getDescription());
}
}
最佳答案
需要在 printNote 函数中进行更改。
当 Notes 的构造函数初始化时,pages 变量将使用 NotePage LinkedList 进行初始化。 页面不直接包含值。它包含 NotePage 的对象。因此,您需要使用循环遍历所有 linkedList 对象,然后打印每个对象的标题和描述。
void printNote(){
System.out.println(getTitle());
//no need to use getPages function, pages already has your list
for(int i=0; i<pages.size();i++)
System.out.println(pages.get(i).getTitle()+"\n"+pages.get(i).getDescription());
}
get 函数将帮助您获取每个第 i 个索引处的对象,然后只需使用 NotePage 类的 get 函数即可打印标题和描述。
另外,在 main 函数中,将 linkedList 对象添加到 Note 的构造函数中,而不是 NotePage。
LinkedList<NotePages> notelist = new LinkedList<>();
notelist.add(page);
//adding LinkedList object to Notes constructor
Notes note = new Notes("Note one", notelist);
关于java - 如何正确显示对象内对象的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57740711/