如何从Java中的Stack接收上一行文本

问题描述 投票:0回答:3

我目前正在努力使用代码。问题主要发生在阵列上并试图回到原点。

此文件只需要一个main方法,在用户输入“quit”之前执行以下操作:

•提示用户访问URL,返回(仅在可能的情况下)或退出

•访问并显示输入的URL

•返回并显示以前访问过的URL(如果可能)

•如果用户在没有要返回的页面时输入“返回”,则应显示相应的消息。

这是一个输出的例子:

输入网址或“退出”:返回

没有要返回的网址

输入网址或“退出”:http://www.wwe.com

当前网址:http://www.wwe.com

输入网址或“退出”:返回

没有要返回的网址

当前网址:http://www.wwe.com

输入网址或“退出”:http://www.amazon.com

当前网址:http://www.amazon.com

输入网址,“返回”或“退出”:http://www.google.com

当前网址:http://www.google.com

输入网址,“返回”或“退出”:返回

当前网址:http://www.amazon.com

输入网址,“返回”或“退出”:返回

当前网址:http://www.wwe.com

输入网址或“退出”:退出

这是我目前的代码:

public class BrowsingHistory
{
 public static void main(String [] args)
 {

    Scanner url = new Scanner(System.in);
    String web = "";
    String currentURL = "";
    Stack<String> myStack = new Stack<>();
    System.out.print("Enter a URL or \"quit\": ");
    web = url.nextLine();
    while (!web.contains("quit"))
    {
        System.out.println();
        System.out.print("Enter a URL, \"back\", or \"quit\": ");
        web = url.nextLine();
        if(web.equals("back") && myStack.isEmpty())
        {
            System.out.println("No URL to go back to");

        }
            else if(!web.equals("back"))
            {
                myStack.push(web);
                System.out.println("Current URL: " + myStack.peek());
            }
            else
                {
                    System.out.println("No URL to go back to");
                    System.out.println("Current URL: " + myStack.pop());
        }
        }
}
}

以下是需要通过的测试,只是澄清了:

 @Test
 void testMain()
 {
     setInput("back\nhttp://www.uwec.edu\nback\nhttp://www.amazon.com\nhttp://.    w.google.com\nback\nback\nquit\n");

BrowsingHistory.main(null);

 String mainOutput = outContent.toString();

  Scanner driverOut = new Scanner(mainOutput);

     String outputLine = getNextOutputLine(driverOut);

    assertEquals("Enter a URL or \"quit\":", outputLine.substring(0, outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (initial prompt problem)");

错误发生在下面这一行:

    assertEquals("No URL to go back to", outputLine.substring(outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (can't go back issue)");

其余的通过:

    outputLine = getNextOutputLine(driverOut);
    assertEquals("Enter a URL or \"quit\":", outputLine.substring(0, outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (prompt problem)");
    assertEquals("Current URL: http://www.uwec.edu", outputLine.substring(outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (current url problem)");

    outputLine = getNextOutputLine(driverOut);
    assertEquals("Enter a URL or \"quit\":", outputLine.substring(0, outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (prompt problem)");
    assertEquals("No URL to go back to", outputLine.substring(outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (can't go back issue)");

    outputLine = getNextOutputLine(driverOut);
    assertEquals("Current URL: http://www.uwec.edu", outputLine.trim(), "BrowsingHistory doesn't run as expected (current url problem)");

    outputLine = getNextOutputLine(driverOut);
    assertEquals("Enter a URL or \"quit\":", outputLine.substring(0, outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (prompt problem)");
    assertEquals("Current URL: http://www.amazon.com", outputLine.substring(outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (current url problem)");

    outputLine = getNextOutputLine(driverOut);
    assertEquals("Enter a URL, \"back\", or \"quit\":", outputLine.substring(0, outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (prompt problem)");
    assertEquals("Current URL: http://www.google.com", outputLine.substring(outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (current url problem)");

    outputLine = getNextOutputLine(driverOut);
    assertEquals("Enter a URL, \"back\", or \"quit\":", outputLine.substring(0, outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (prompt problem)");
    assertEquals("Current URL: http://www.amazon.com", outputLine.substring(outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (current url problem)");

    outputLine = getNextOutputLine(driverOut);
    assertEquals("Enter a URL, \"back\", or \"quit\":", outputLine.substring(0, outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (prompt problem)");
    assertEquals("Current URL: http://www.uwec.edu", outputLine.substring(outputLine.indexOf(":")+1).trim(), "BrowsingHistory doesn't run as expected (current url problem)");

    outputLine = getNextOutputLine(driverOut);
    assertEquals("Enter a URL or \"quit\":", outputLine.trim(), "BrowsingHistory doesn't run as expected (prompt problem)");

    assertFalse(driverOut.hasNext(), "BrowsingHistory doesn't run as expected (quit problem)");

    driverOut.close();
}
java stack
3个回答
2
投票

使用Stack类而不是ArrayList将使您的生活更轻松。

使用push()将新url添加到堆栈。

使用empty()检查是否可以返回。

使用pop()返回。

编辑 - 支持前进

如果您还想支持“前向”命令,则可以使用第二个堆栈并将该历史堆栈中弹出的URL推送到该前向堆栈。当输入'forward'命令时,检查前向堆栈是否为空,如果不是,则从那里弹出url并将其推回到历史堆栈。

编辑2 - 示例代码

以下是解释2堆栈解决方案的一些基本代码:

Stack<String> historyStack = new Stack<>();
Stack<String> forwardStack = new Stack<>();
String currentUrl = null;

boolean running = true;
while(running) {
    String input = getUserInput();
    switch(input) {
        case "quit":
            running = false;
            break;
        case "back":               
            if (!historyStack.empty()) {
                if (currentUrl != null) {
                    forwardUrl.push(currentUrl);
                }
                currentUrl = historyStack.pop();
                System.out.println(currentUrl);
            } else {
                System.out.println("nothing to go back to");
            }
            break;
        case "forward":
            if (!forwardStack.empty()) {
                if (currentUrl != null) {
                    historyStack.push(currentUrl);
                }
                currentUrl = forwardStack.pop();
                System.out.println(url);
            } else {
                System.out.println("nothing to go forward to");
            }
            break;
        default:
            if (currentUrl != null) {
                historyStack.push(currentUrl);
            }
            currentUrl = input;
            System.out.println(url);
            // entering a new url makes forward stack invalid
            forwardStack.clear();
    }
}

1
投票

您可以将逻辑更改为:

ArrayList<String> webs = new ArrayList<String>();
String web = "";
Scanner url = new Scanner(System.in);

int count = 0;
while (!web.contains("quit")) {
    System.out.println("Enter a URL or \"quit\":");
    web = url.next();
    if (!web.equals("back")) {
        webs.add(web);
        count = webs.size();
    } else if (web.equals("back") && !webs.isEmpty()) {
        if (count > 0) {
            count--;
            System.out.println(webs.get(count));
        } else {
            System.out.println("No url to go back to");
        }
    }
}

请注意以下几点:

  1. 我们只添加不等于后面的字符串
  2. 在您之前的实现中,输入的第一个网址未插入您的列表中。
  3. 将元素添加到列表后,count将重置为列表的大小。

正如其他人所指出的那样,使用Stack可以更容易地实现同样的目的

Scanner url = new Scanner(System.in);
String web = "";
Stack<String> myStack = new Stack<>();
while (!web.contains("quit")) {
    System.out.println("Enter a URL or \"quit\":");
    web = url.next();
    if (!web.equals("back") && !web.equals("quit")) {
        myStack.push(web);
    } else {
        if (!myStack.isEmpty()) {
            System.out.println(myStack.pop());
        } else {
            System.out.println("No url to go back to");
        }
    }
}

0
投票

您使用不正确的数据结构。 List没关系,但是使用Stack在这里更正确:你添加到最后并从最后检索,这个ID是LIFO。

private static final String QUIT = "quit";
private static final String BACK = "back";

try (Scanner url = new Scanner(System.in)) {
    Deque<String> stack = new LinkedList<>();

    while (true) {
        System.out.print("Enter a URL, \"" + BACK + "\" or \"" + QUIT + "\": ");
        String str = url.next();

        if (str.equalsIgnoreCase(QUIT))
            break;
        else if (str.equalsIgnoreCase(BACK)) {
            if (!stack.isEmpty())
                stack.pop();
            System.out.println(stack.isEmpty() ? "No URL to go back to" : stack.element());
        } else
            stack.push(str);
    }
}

演示

Enter a URL, "back" or "QUIT": http://www.wwe.com
Enter a URL, "back" or "QUIT": http://www.amazon.com
Enter a URL, "back" or "QUIT": http://www.google.com
Enter a URL, "back" or "QUIT": back
http://www.amazon.com
Enter a URL, "back" or "QUIT": back
http://www.wwe.com
Enter a URL, "back" or "QUIT": back
No URL to go back to
Enter a URL, "back" or "QUIT": quit
© www.soinside.com 2019 - 2024. All rights reserved.