// CSE 143, Summer 2016 // // A handy example of keeping track of web pages visited. import java.util.*; // An example showing a back button used in a browser. A perfect // application for a stack, a "last in, first out (lifo)" data // structure. public class BackButton { public static void main(String[] args) { Stack pages = new Stack(); visit("google.com", pages); visit("reddit.com", pages); System.out.println(pages); System.out.println(); goBack(pages); System.out.println(pages); goBack(pages); } // pre : pages should not be null (throws IllegalArgumentException otherwise) // post: adds page to pages, and pronounces the page as being visited public static void visit(String page, Stack pages) { if (pages == null) { throw new IllegalArgumentException(); } System.out.println("Visiting " + page + "..."); pages.push(page); } // pre : pages should not be null (throws IllegalArgumentException otherwise) // post: takes a page from the top of pages, and says that the page is being // left. Also prints the current page, if there is one left. public static void goBack(Stack pages) { if (!pages.isEmpty()) { // Someone in class was talking about the one line version. // The below is the equivalent one line version. // --- // System.out.println("Leaving " + pages.pop() + "..."); String oldPage = pages.pop(); System.out.println("Leaving " + oldPage + "..."); if (!pages.isEmpty()) { // The below is equivalent. // --- // String currentPage = pages.pop(); // System.out.println("Currently on " + currentPage); // pages.push(currentPage); // --- String currentPage = pages.peek(); System.out.println("Currently on " + currentPage); } else { System.out.println("No page left!"); } } else { System.out.println("No page!"); } } }