此程序用于闪存卡应用程序。我的构造函数使用了一个链表,但问题是,当我使用一个方法列出特定盒子中的卡片时,它不会打印期望的结果。系统应该打印"瑞恩·哈丁"。而是打印"Box$NoteCard@68e86f41"。有人能解释为什么会发生这种情况,我能做些什么来解决这个问题吗?我还附上了我的盒子和卡片类。
import java.util.LinkedList;
import java.util.ListIterator;
public class Box {
public LinkedList<NoteCard> data;
public Box() {
this.data = new LinkedList<NoteCard>();
}
public Box addCard(NoteCard a) {
Box one = this;
one.data.add(a);
return one;
}
public static void listBox(Box a, int index){
ListIterator itr = a.data.listIterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
public static void main(String[] args) {
NoteCard test = new NoteCard("Ryan", "Hardin");
Box box1 = new Box();
box1.addCard(test);
listBox(box1,0);
}
}
这是我的NoteCard类
public class NoteCard {
public static String challenge;
public static String response;
public NoteCard(String front, String back) {
double a = Math.random();
if (a > 0.5) {
challenge = front;
} else
challenge = back;
if (a < 0.5) {
response = front;
} else
response = back;
}
public static String getChallenge(NoteCard a) {
String chal = a.challenge;
return chal;
}
public static String getResponse(NoteCard a) {
String resp = response;
return resp;
}
public static void main(String[] args) {
NoteCard test = new NoteCard("Ryan", "Hardin");
System.out.println("The challenge: " + getChallenge(test));
System.out.println("The response: " + getResponse(test));
}
}
尝试在class NoteCard
中重写toString()方法。
@Override
public String toString()
{
//Format your NoteCard class as an String
return noteCardAsString;
}
首先你使用了太多的static keyword
。我不确定你是否需要那个。
无论如何,创建两个实例变量front和back,并在NoteCard类的构造函数中为其赋值,同时实现toString方法
public class NoteCard {
public static String challenge;
public static String response;
public String front;
public String back;
public NoteCard(String front, String back) {
//your code
this.front = front;
this.back = back;
}
@Override
public String toString()
{
//return "The challenge:" + challenge + " " + "The response: " + response;
return "The Front:" + front + " " + "The Back: " + back;
}
注意:由于实例方法toString()是隐式继承的将toString()方法声明为子类型中的静态方法导致编译时错误,所以不要将此方法设为STATIC