首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为队列创建toString

为队列创建toString
EN

Stack Overflow用户
提问于 2017-12-02 06:17:48
回答 3查看 2.7K关注 0票数 0

我正在尝试为一个queue类创建一个toString方法,该类以数组格式返回队列的字符串,队列中的最后一个值是字符串中的第一个值。例如,如果按此顺序将1,2,3,4,5添加到队列中,则toString方法将返回5,4,3,2,1。

我尝试过这样做,但似乎无法获得要打印的最后一个值。

下面是我目前使用的toString方法

代码语言:javascript
复制
    public String toString( ) {
    if ( isEmpty() ) {
        return "[]";
    } else {

        String build = "";

        Node current = first;
        while ( current.getNext() != null ) {
            build = current.getElement() + ", " + build;
            current = current.getNext();
        }

        return "[" + build + "]";
    }
}

}

当我按如下方式进行测试时:

代码语言:javascript
复制
public class test {

public static void main( String[] args ){

    Queue q = new Queue(5);

    try {
        q.enqueue(1);
        q.enqueue(2);
        q.enqueue(3);
        q.enqueue(4);
        q.enqueue(5);

        System.out.println(q.toString());

    } catch (QueueFullException e ) {
        e.printStackTrace();
    }
}

}

我一直在想:

代码语言:javascript
复制
[4, 3, 2, 1, ]

任何帮助都是非常感谢的。谢谢

EN

回答 3

Stack Overflow用户

发布于 2017-12-02 07:08:58

这种方法是可行的:

代码语言:javascript
复制
@Override
public String toString ()
{
    String build = "";

    // I didn't want to make an assumption here - I don't know your implementation
    // If first is null when the queue is empty, then simplify this line
    Node current = (isEmpty()) ? null : first;

    while ( current != null )
    {
        String currElem = String.valueOf(current.getElement());

        // don't add the comma after the first element
        build = (build.length() == 0) ? currElem : currElem + ", " + build;

        current = current.getNext();
    }

    return "[" + build + "]";
}

注意:您不需要空队列的特殊情况-因为构建字符串将为空。

票数 1
EN

Stack Overflow用户

发布于 2017-12-02 06:27:18

请尝试执行以下操作

代码语言:javascript
复制
while ( current.getNext() != null ) {
             build = current.getElement() + ", " + build;
              current = current.getNext();
         } 
build = current.getElement() + build; // get the value of the last element

因为在最后一个元素中没有next,但应该打印最后一个值

票数 0
EN

Stack Overflow用户

发布于 2019-06-05 12:40:26

您正在使用current.getNext()检查遍历队列元素。您可以使用

代码语言:javascript
复制
public String toString( ) {
if ( isEmpty() ) {
    return "[]";
} else {

    String build = "";

    Node current = first;
    while ( current != null ) {
        build = current.getElement() + ", " + build;
        current = current.getNext();
    }

    return "[" + build + "]";
}

这将解决您的问题。谢谢。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47602270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档