java - 方法 isEmpty() 对于类型 InputStream 错误未定义

标签 java algorithm stack

我正在尝试获取堆栈弹出算法的链表实现。这是完整的代码。该代码实际上来自 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/

相关文章:

java - 使用 Volley 与 ESP8266 与 AndroidApp 通信

java - 在分离的 Java 平台模块中使用不同版本的依赖项

php - 检查一个数组是否可以放入另一个数组

C++ Stack 实现意外输出

c - 在 C 中,大括号是否充当堆栈框架?

java - 从数据库中的推文中删除停用词和超链接

java - 我使用的是哪个 JRE?

python - Python 中点画派绘画的随机化算法

algorithm - DAG - 确保存在单一源和单一汇的算法

algorithm - 为什么我们做 "implement a queue using 2 stacks"?