我正在尝试为一个queue类创建一个toString方法,该类以数组格式返回队列的字符串,队列中的最后一个值是字符串中的第一个值。例如,如果按此顺序将1,2,3,4,5添加到队列中,则toString方法将返回5,4,3,2,1。
我尝试过这样做,但似乎无法获得要打印的最后一个值。
下面是我目前使用的toString方法
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 + "]";
}
}}
当我按如下方式进行测试时:
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();
}
}}
我一直在想:
[4, 3, 2, 1, ]任何帮助都是非常感谢的。谢谢
发布于 2017-12-02 07:08:58
这种方法是可行的:
@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 + "]";
}注意:您不需要空队列的特殊情况-因为构建字符串将为空。
发布于 2017-12-02 06:27:18
请尝试执行以下操作
while ( current.getNext() != null ) {
build = current.getElement() + ", " + build;
current = current.getNext();
}
build = current.getElement() + build; // get the value of the last element因为在最后一个元素中没有next,但应该打印最后一个值
发布于 2019-06-05 12:40:26
您正在使用current.getNext()检查遍历队列元素。您可以使用
public String toString( ) {
if ( isEmpty() ) {
return "[]";
} else {
String build = "";
Node current = first;
while ( current != null ) {
build = current.getElement() + ", " + build;
current = current.getNext();
}
return "[" + build + "]";
}这将解决您的问题。谢谢。
https://stackoverflow.com/questions/47602270
复制相似问题