Why is it that my stack isn't working?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • babe20042004
    New Member
    • Oct 2008
    • 8

    Why is it that my stack isn't working?

    I have a program that reads the names of countries from a file, prints them to the screen then prints thm from the stack. However when it prints from the stack this is the resulting output:

    Returning what is in the stack

    Country@42e816
    Country@9304b1
    Country@190d11
    Country@a90653

    Can someone help me please?
    This is the code:
    Code:
    import java.io.*;
    
    public class StackOfObjects {
        private Node first;
        
        
        private class Node {
            private Object item;
            private Node next;
        }
    
        
        public StackOfObjects() {
            first = null;
        }
    
        
        public boolean isEmpty() { return (first == null); }
    
        
        public void push(Object item) {
            Node oldfirst = first;
            first = new Node();
            first.item = item;
            first.next = oldfirst;
        }
    
        
        public Object pop() {
            if (isEmpty()) throw new RuntimeException("Stack underflow");
            Object item = first.item;      
            first = first.next;            
            return item;                   
        }
    
    
        // a test client
        public static void main(String[] args) {
            StackOfObjects stack = new StackOfObjects();
           
     	   
     	   try{
     		   
     		    FileInputStream fstream = new FileInputStream("textfile.txt");
     		    
     		    DataInputStream in = new DataInputStream(fstream);
     		        BufferedReader br = new BufferedReader(new InputStreamReader(in));
     		    String strLine;
     		   System.out.println ("Returning what is in the file\n");
     		    
     		    while ((strLine = br.readLine()) != null)   {
     		    	
     			      System.out.println (strLine);
     		    	Country count=new Country();
     		    	count.name=strLine;
     		    	stack.push(count);
     		    	
     		      
     		    }
     		   System.out.println ("\nReturning what is in the stack\n");
     		    while( ! stack.isEmpty() ){
     		    	Object s=(Object) stack.pop();
     		        System.out.println(s);
     		    }
    
     		    
     		    in.close();
     		    }catch (Exception e){
     		      System.err.println("Error: " + e.getMessage());
     		}
            
        }
    }
    Code:
    public class Country {
    	String name;
    
    }
  • babe20042004
    New Member
    • Oct 2008
    • 8

    #2
    I got it to work
    Code:
    while( ! stack.isEmpty() ){
    Country s=(Country) stack.pop();
    System.out.println(s.name);
    }

    Comment

    Working...