【问题标题】:JOptionDialog display Stacks How to?JOption Dialog 显示 Stacks 如何?
【发布时间】:2014-10-20 18:45:10
【问题描述】:

好吧,我需要在这个实验室中显示我在 JOptionMessageDialog 框中创建的堆栈,但我不知道如何显示堆栈。我一直显示@jkh24k54 而不是整数集。??

我的代码:

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());

} }

【问题讨论】:

  • 最后一行是我需要的。

标签: java dialog stack message joptionpane


【解决方案1】:

您调用 Object 的默认 toString() 方法,该方法默认打印其内存位置,这就是您获得 @jkh24k54 的原因。您需要覆盖堆栈类的 toString() 方法以返回数组中元素的字符串。

一个例子:在你的 Stack 类中添加这样的东西。

@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;
}

【讨论】:

  • 它不会按说打印内存位置;它打印出它的哈希码,在某些情况下(我认为它是 java8+)是内存位置。
  • 我该怎么做?根据本实验室的要求,我无法在我的代码中创建实际字符串。
  • 足够好,它有效。他可能会数数,但我还有 20 分钟的工作。只有另一个问题是,当我这样做时,我会得到一些数字和数组中每个空槽的“null”,最多 20 ..有没有办法解决这个问题?
  • 如果 returnString 为 == null 则不要添加元素。
  • 你也可以投票并标记为正确。他不应该算错,因为这是做你想做的事情的正确方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多