I have a class designed to implement the basics of a stack into web browser urls.
The intended behavior is as follows If the user types a URL into the address bar, the forward stack is cleared. If the user clicks the back button, the current URL (in the address bar) is pushed onto the forward stack. The back stack is popped, and the popped URL is placed in the address bar. If the back stack is empty, nothing happens. If the user clicks the forward button, the current URL (in the address bar) is pushed onto the back stack. The forward stack is popped, and the popped URL is placed in the address bar If the back forward stack is empty, nothing happens.
Basically, I'm running into an issue with dealing with the back stack. Each time the back stack block is called, the current url is pushed into the forward stack. While this behavior is correct for one push of the back stack, it is unintended for when the back stack no longer moves back (Example: Google.com [back stack call] Google.com, pushes Google.com to the forward stack twice).
I'm having trouble thinking of the logic to not allow this to happen. It's clearly incorrect behavior to have to push the forward stack multiple times to only move up one webpage.
Any suggestions while keeping my the core of my code intact?
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 + "]");
}
}
}
url?elsestatement at the bottom,url = input