2015-10-13 84 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()爲靜態的子類型 導致編譯時錯誤所以不要使這個方法靜態

相關問題