需要帮助使用堆栈以相反的顺序打印字符串(查看详情)

时间:2016-11-08 18:59:14

标签: java stack

我设法让我的代码编译但是我试图创建一个接受用户输入的程序并使用push()方法将该字符串添加到堆栈中。我正在使用其他反转输入顺序的方法。例如,用户输入几个字符串: "你好" "世界" "!" 然后,一旦用户键入"结束"作为输入,程序将停止推送到堆栈并以相反的顺序打印,如下所示: "!" "世界" "你好"

以下是我的代码:

public class stackReversal {

    private Node first = null;

    private class Node {
        private String item;
        private Node next;
}

    public boolean isEmpty() {
        return (first == null);
}

    public void push(String s) {
        Node node = new Node();
        node.item = s;
        node.next = first;
        first = node;
}

    public String pop() {
        if (first == null)
            throw new RuntimeException("Stack Empty!");
        String result = first.item;
        first = first.next;
        return result;
}

    public String popString() {
        String result = "";
        Node current = first;
        while (current != null) {
            result += current.item;
            current = current.next;
}
        return result;
}

    public String toString() {
        StringBuilder nodes = new StringBuilder();
        Node node = first;
        while (node != null) {
            nodes.append(node.item);
            node = node.next;
}
        if (isEmpty()) {
            return "";
        } else {
            return nodes.toString().substring(0, nodes.toString().length() -      4);
        }
}

    public static void main(String[] args) {
        stackReversal s = new stackReversal();
        Scanner input = new Scanner(System.in);
        System.out.print("Enter strings:");
        String in = input.nextLine();
        while (!in.equals("end-of-input")) {
            s.push(in);
            if (in.equals("end"))
                break;
        }
        System.out.println("Strings:" + s);
    }
}

1 个答案:

答案 0 :(得分:0)

你的循环根本没有用,你没有任何结束条件。

将主要方法更改为以下内容:

public static void main(String[] args)
{
    StackReversal s = new StackReversal();
    Scanner input = new Scanner(System.in);
    System.out.print("Enter strings:");
    String in = "";
    while (!in.equals("end"))
    {
        in = input.nextLine();
        if (in.equals("end"))
            break;
        else
            s.push(in);
    }
    System.out.println("Strings:" + s);
}
  1. end-of-string和end应该是相同的条件。所以只需end
  2. input.nextLine();需要在循环中并且每次都分配到in
  3. s.push(in);应该在else语句中,以避免将end添加到堆栈中。
相关问题