gpt4 book ai didi

java - 为什么我的 Java 代码中会出现此输出?

转载 作者:行者123 更新时间:2023-12-01 07:35:15 25 4
gpt4 key购买 nike

The student at the top of the stack is Gullion,Hailey

Student Mcglothlen,Shizue is removed from the stack


Here are all the elements of the Stack using an Iterator
--------------------------------------------------------
Stack$Node@3012db7c
Stack$Node@2607c28c
Stack$Node@477588d5
Stack$Node@756a7c99
Stack$Node@221a5d08
Stack$Node@70d1c9b5
Stack$Node@5d11c3f0
Stack$Node@3956f14c
Stack$Node@7afbd1fc
null


Here are all the elements in the Stack
--------------------------------------
Putney,John
Larkey,Ismael
Winkler,Isiah
Aceto,Liana
Hamill,Crissy
Caraway,Elmira
Gullion,Hailey
Rodrigez,Jonie
Madruga,Terrell
Williams,Diego

使用迭代器的堆栈的第一个元素列表显然不起作用。我不知道为什么。这是我的 Stack 类中的 Iterator 代码:

public Iterator<Student> iterator()  { return new ListIterator();  }

// an iterator, doesn't implement remove() since it's optional
private class ListIterator implements Iterator<Student> {
private Node<Student> current = top;

public boolean hasNext() {
return current != null;
}

public void remove() {
throw new UnsupportedOperationException();


@SuppressWarnings("unchecked")
public Student next() {
if (!hasNext()) throw new NoSuchElementException();
current = current.next;
return (Student)current;
}
}

这是我的 Driver 类中似乎存在问题的代码:

System.out.println("\nHere are all the elements of the Stack using an Iterator");
System.out.println("--------------------------------------------------------");
Iterator <Student> iter = myStack.iterator();
while (iter.hasNext() )
System.out.println(iter.next() );

这是所有类(class):

堆栈:http://pastebin.com/2HVLVHuM

队列类:http://pastebin.com/3q537kHW

学生类(class):http://pastebin.com/UnBB7kPA

驱动程序类别:http://pastebin.com/yeA34MNd

我只能在 Stack 类中编写代码。这样做的目的是使用队列实现堆栈。希望这有帮助

最佳答案

您需要在 Student 类中添加一个 toString() 方法。迭代器工作正常,但 System.out.println() 不知道如何显示 Student

Student 类中添加一些内容,如下所示...

public String toString(){
return name;
}

这样当你调用System.out.println()时,它就可以输出一个真实的值。当您调用 System.out.println(Object) 时,它总是尝试输出 toString() 值。如果未定义此方法,它将输出对象的 java ID,这就是您所看到的。

关于java - 为什么我的 Java 代码中会出现此输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12966285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com