首页 > 解决方案 > 对于 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 新手

标签: javaalgorithmstack

解决方案


编辑; 您正在尝试从 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);
            }
        }
    }

推荐阅读