为什么这不打印对象内的String?

时间:2015-10-13 05:43:05

标签: java arrays linked-list

此程序用于闪存卡应用程序。我的构造函数使用链接列表,但问题是,当我使用一种方法列出特定框内的卡时,它不会打印所需的结果。系统应打印" Ryan Hardin"。相反,它是印刷" 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));
}
}

2 个答案:

答案 0 :(得分:0)

尝试覆盖class NoteCard中的方法toString()。

@Override
public String toString()
{
  //Format your NoteCard class as an String

  return noteCardAsString;
}

答案 1 :(得分:0)

首先,你过分使用static keyword。我不确定你是否需要那个。
无论如何都要在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()是隐式继承的   从Object,在子类型中将方法toString()声明为静态   导致编译时错误,因此不要将此方法设置为静态