Okay guys I need for this Lab is to display stacks that I made in JOptionMessageDialog box and I have no idea how to display the stack. I keep displaying @jkh24k54 instead of the set of integers.??
My code:
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());
} }
Your calling the default toString() method of an Object which prints its memory location by default that is why you are getting @jkh24k54. You need to override the toString() method of your stack class to return a string of the elements in your array.
An example: add something like this to your Stack Class.
@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;
}