java - 对于 InputStream 类型错误,方法 isEmpty() 未定义
问题描述
我正在尝试获取堆栈弹出算法的链表实现。这是完整的代码。代码实际上来自 Coursera 的课程算法,第 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);
}
}
}
推荐阅读
- angular - 如何在角度6中的ngb-progressbar的值字段中分配动态值
- angular - 我可以在 Angular 6 单元测试中使用“this”吗?
- python - Virtualenv 需要 env
- c++ - SFINAE 是否依赖于类型扣除?
- ios - 在 SpriteKit 场景之间传递数据 (Swift)
- postgresql - 我们正面临“恐慌:无法从控制文件中读取:成功
- php - Joomla!- 将类添加到菜单中的标签
- javascript - Symfony 复选框默认选中,但如果在持久化后未选中则不会
- javascript - Jestjs如何测试在另一个函数中调用的函数
- c - 在 Ubuntu 16.04 上找不到 printf.c