1

I am trying to write a stack code using Java for getting browsing history for 100 data. I wrote this code but I am not sure this program satisfies first in last out rule and also most importantly I don't want to write lastvisit = browsing.pop(); for 100 times for 100 data. What can I do for it?

import java.util.Stack;

public class Browser {
    
    public static void main(String[] args) {
       
        Stack<String> browsing = new Stack<>();

        
        browsing.push("google.com");
        browsing.push("facebook.com");
        browsing.push("twitter.com");
        browsing.push("youtube.com");

        System.out.println("Browsing History " + browsing);
        System.out.println();

        
        String lastvisit = browsing.pop();  
        System.out.println("lastvisit " + lastvisit);
        System.out.println("Browsing History " + browsing);
        System.out.println();

       
        lastvisit = browsing.pop();
        System.out.println("lastvisit " + lastvisit);
        System.out.println("Browsing History " + browsing);
        lastvisit = browsing.pop();  
        System.out.println("lastvisit " + lastvisit);
        System.out.println("Browsing History " + browsing);
    }   
}
1
  • 1
    A list would make more sense to store a browsing history. Commented Dec 20, 2021 at 18:55

2 Answers 2

1

The JDK's Stack class indeed implements the "first in last out" (more commonly known as "last in first out", or LIFO) rule.

One way to go over the entire history would be to loop over the stack until it's empty:

while (!browsing.empty()) {
    String lastvisit = browsing.pop();  
    System.out.println("lastvisit " + lastvisit);
    System.out.println("Browsing History " + browsing);
    System.out.println();
}
Sign up to request clarification or add additional context in comments.

Comments

0

I updated the code with string array and added @Mureinik 's answer. Final clean code:

import java.util.*; 
import java.util.Stack;

public class Browser {
    
    public static void main(String[] args) {
           List<String> urls = Arrays.asList("facebook.com*mehmet.com+google.com-kesimalioglu.com/youtube.com".split("[\\*+/-]"));

        Stack<String> browsing = new Stack<String>();
    for(String str : urls)
        browsing.add(str);
        
        

        System.out.println("Browsing History " + browsing);
        System.out.println();

        
        while (!browsing.empty()) {
    String lastvisit = browsing.pop();  
    System.out.println("lastvisit " + lastvisit);
    System.out.println("Browsing History " + browsing);
    System.out.println();
}

    }
    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.