2014-10-20 44 views
0

好的傢伙我需要這個實驗室是顯示堆棧,我在JOptionMessageDialog框中,我不知道如何顯示堆棧。我繼續顯示@ jkh24k54而不是整數集。JOptionDialog顯示堆棧如何?

我的代碼:

import java.util.Random; 
import javax.swing.JOptionPane; 

public class Lab5 
{ 

    public static void main(String[] arg) 
    { 

Random rnd = new Random(); 

Stack<Integer> stack = new IStack<Integer>(); 
Stack<Integer> stack0= new IStack<Integer>(); 
Stack<Integer> stack1= new IStack<Integer>(); 
Stack<Integer> stack2= new IStack<Integer>(); 
int stream; 


for(int i=0;i<20;i++) 
{ 
    stream = rnd.nextInt(101); 
    stack.push(stream); 
    stack2.push(stream); 
} 
while(!stack2.isEmpty()) 
{ 
    int x = stack2.pop(); 
    stack.push(x); 
} 

    for(int i=0; i<20; i++) 
    { 
    int x= stack.pop(); 

    if(x%3==0) 
    stack0.push(x); 
    if(x%3==1) 
    stack1.push(x); 
    if(x%3==2) 
    stack2.push(x); 
} 

    while(!stack.isEmpty()) 
     System.out.print(stack.pop()+" "); 
    System.out.println(); 
    while(!stack0.isEmpty()) 
     System.out.print(stack0.pop()+" "); 
    System.out.println(); 
    while(!stack1.isEmpty()) 
     System.out.print(stack1.pop()+" "); 
    System.out.println(); 
    while(!stack2.isEmpty()) 
     System.out.print(stack2.pop()+" "); 
    System.out.println(); 

JOptionPane.showMessageDialog(null, "Original stack: "+ stack.toString()+ "\n"+ 
           " 0%3: "+stack0.toString()+"\n"+ "1%3: "+stack1.toString()+"\n"+ " 2%3: "+stack2.toString()); 

}}

+0

最後一行是我需要的。 – 2014-10-20 18:46:07

回答

2

您的通話在默認情況下,這就是爲什麼你得到@ jkh24k54打印其存儲位置的對象的默認toString()方法。您需要重寫堆棧類的toString()方法以返回數組中的元素的字符串。

一個例子:像這樣的東西添加到你的堆棧類。

@Override 
public String toString() 
{ 
    String returnString = ""; 
    for(int i = 0; i < yourarray.length; i++) 
    { 
     if(yourarray[i] != null) 
     { 
      returnString += yourarray[i]; 
     } 
     ////if you want to add spaces for null then add this 
     else 
     { 
      returnString += " "; 
     } 
     ////the else is probably not necessary for what you are doing 
    } 
    return returnString; 
} 
+0

它不打印每個說的內存位置;它打印出它的哈希碼,在某些情況下(我認爲它是java8 +)是內存位置。 – Pokechu22 2014-10-20 18:48:15

+0

我該怎麼做? 根據本實驗的要求,我無法在自己的代碼中創建實際的字符串。 – 2014-10-20 18:48:21

+0

夠好,它工作。他可能會計數,但我有20分鐘的工作。只有其他問題是,當我這樣做時,我得到了一些數字和數組中的每個空插槽「空」到20 ..有沒有辦法解決這個問題? – 2014-10-20 18:57:11