java - 堆栈行为的正确实现

标签 java stack

我有一个类,旨在将堆栈的基础知识实现到 Web 浏览器 URL 中。

预期行为如下 如果用户在地址栏中键入 URL,则转发堆栈将被清除。 如果用户单击后退按钮,则当前 URL(在地址栏中)将被推送到前进堆栈上。返回堆栈被弹出,弹出的 URL 被放置在地址栏中。如果返回堆栈为空,则不会发生任何事情。 如果用户单击前进按钮,则当前 URL(在地址栏中)将被插入后退堆栈。向前堆栈弹出,弹出的URL放置在地址栏 如果后退堆栈为空,则不会发生任何事情。

基本上,我在处理返回堆栈时遇到了问题。每次调用后退堆栈 block 时,当前 url 都会被插入前向堆栈。虽然此行为对于向后堆栈的一次推送是正确的,但当向后堆栈不再向后移动时,这是无意的(例如:Google.com [向后堆栈调用] Google.com,将 Google.com 推送到前向堆栈两次) .

我无法思考不允许这种情况发生的逻辑。必须多次推送前向堆栈才能仅向上移动一个网页,这显然是不正确的行为。

在保持代码核心完整的同时,有什么建议吗?

public class BrowserStack {

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);

        // the current URL
        String url = null;

        Stack<String> forward = new Stack<String>();
        Stack<String> back = new Stack<String>();

        String input;
        System.out.println("Type a combination of URLs, or the > or < symbol.\nType 'q' to quit.");

        while (true) {

            input = s.next();

            if (input.equals("q")) {
                System.out.println("Bye");
                return;
            }

            if (input.equals("<")) {
                try {
                    forward.push(url); //unintended behavior happens here
                    url = back.pop();
                } catch (EmptyStackException e) {
                }
            }

            else if (input.equals(">")) {
                try {
                    back.push(url);
                    url = forward.pop();
                } catch (EmptyStackException e) {
                }
            }

            else {
                if (url != null)
                    back.push(url);
                url = input;
                forward.clear();
            }
            System.out.println("Current webpage [" + url + "]");
        }
    }
}

最佳答案

交换您的入栈/出栈顺序,以便在入栈之前退出 try/catch:

if (input.equals("<")) {
    try {
        String temp = url;
        url = back.pop();
        forward.push(temp); // this only executes if the last line completed unexceptionally
    } catch (EmptyStackException e) {
    }
}

但更正确的做法是根本不引发异常,而是在弹出之前进行检查:

if (input.equals("<")) {
    if (!back.isEmpty());
        forward.push(url);
        url = back.pop();
    }
}

关于java - 堆栈行为的正确实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37153403/

相关文章:

java - 为什么 Hibernate JPA 在使用 getReference() 时抛出 LazyInitialization 异常?

java - 在 Android 中使用 Windows Azure 服务总线队列

java - 使用 XMLslurper 获取内部数据

c++ - Lua 5.1 中缺少 luaL_len

c - 为什么我在这里收到不兼容的指针类型警告?

c - 堆栈和堆中的变量

java - 如何动态循环数组列表并添加每个第 n 个元素

java - 为什么我的 Android 应用程序在播放后显示 "Cannot play video"?

c - 了解堆栈上变量的空间分配

html - 相互堆叠的 div 标签