我正在尝试获取堆栈弹出算法的链表实现。这是完整的代码。该代码实际上来自 Coursera 中的类(class)算法,第 1 部分。
public class LinkedStackOfString {
private Node first = null;
private class Node {
String item;
Node next;
}
public boolean isEmpty() {
return first == null;
}
public void push(String item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public String pop() {
String item = first.item;
first = first.next;
return item;
}
public static void main(String[] args) {
LinkedStackOfString stack = new LinkedStackOfString();
while (!System.in.isEmpty())
{
String s = System.in.readString();
if (s.equals("-")) System.out.println(stack.pop());
else stack.push(s);
}
}
}
我正在放置完整的错误声明。我收到如下错误消息:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method isEmpty() is undefined for the type InputStream
The method readString() is undefined for the type InputStream
at linkedList/linkedList.LinkedStackOfString.main(LinkedStackOfString.java:30)
谁能解释一下,发生了什么事吗?我是 Java 新手
最佳答案
编辑;您正在尝试从 Scanner 对象获取输入,这就是您引用 System.in 的原因。您需要使用 System.in 作为 InputStream 创建一个新的 Scanner 对象。
public static void main(String[] args) {
LinkedStackOfString stack = new LinkedStackOfString();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String input = scanner.next();
if (input.equals("-")) {
String popped = stack.pop();
System.out.println(String.format("Popped value is %s.", popped));
} else {
stack.push(input);
}
}
}
关于java - 方法 isEmpty() 对于类型 InputStream 错误未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60565957/