2015-10-13 85 views
-2

该程序用于闪存卡应用程序。我的构造函数使用链表,但问题是,当我使用列出特定框内的卡的方法时,它不会打印所需的结果。该系统应打印“瑞安哈丁”。而是打印“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)); 
} 
} 
+1

你是什么意思,没有得到正确的结果。根据你的情况,列表中只能有一个对象。 – saikumarm

+3

你在NoteCard里面实现了toString方法吗?您可以添加NoteCard类 –

+0

适用于我:https://ideone.com/e3HKY4 –

回答

0

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

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

    return noteCardAsString; 
} 
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()方法被隐式地继承 从对象,声明一个方法toString()为静态的子类型 导致编译时错误所以不要使这个方法静态

相关问题