What am I doing wrong with this stack? Java Programming?
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 :
public class Country {
String name;
}
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());
}
}
}
Re: What am I doing wrong with this stack? Java Programming?
It appears to be returning the memory addresses of the items in the stack...I think. I've had this happen a few times before. Try
Code :
System.out.println ("\nReturning what is in the stack\n");
while( ! stack.isEmpty() ){
Object s=(Object) stack.pop();
System.out.println(String.ValueOf(s));
}
Re: What am I doing wrong with this stack? Java Programming?
Passing an object to a PrintStream's print or println will result in the Object's toString() method to be printed. See the API for details on what is printed (Object (Java Platform SE 6) ). In other words, if you want to print more detailed information, override the toString method and return a more detailed string.
Re: What am I doing wrong with this stack? Java Programming?
Thanks to all! I've gotten it to work!
Code :
while( ! stack.isEmpty() ){
Country s=(Country) stack.pop();
System.out.println(s.name);
}