I'm trying to modify the CharStack class (below) in Eclipse, but I'm unable to get it to do anything in the console when I run it, though it works fine when compiled with javac.exe
Is this something to do with carriage returns, perhaps? How do I signal to Eclipse that I'm ready for it to accept the input and return a result (the -1
)?
The algorithm for the class is just:
while (there is a character to read)
push the character onto a stack;
while (there are characters on the stack)
pop off a character and print it;
The concept of a stack is a perfect candidate for becoming a class. It has a well-defined interface (push()
and pop()
) and some rules to enforce (you can only take data from the top, you can only remove as many elements as you insert). Here is a simple implementation of a stack that holds characters:
import java.io.*;
public class CharStack
{
private char[] m_data;
private int m_ptr;
public CharStack(int size)
{
m_ptr = 0;
m_data = new char[(size > 1 ? size : 10)];
}
public void push(char c)
{
if (m_ptr >= m_data.length)
{
// Grow the array automatically
char[] tmp =
new char[m_data.length * 2];
System.arraycopy(m_data, 0,
tmp, 0,
m_data.length);
m_data = tmp;
}
m_data[m_ptr++] = c;
}
public char pop()
{
return m_data[--m_ptr];
}
public boolean hasMoreElements()
{
return (m_ptr != 0);
}
public static void main(String[] argv)
throws IOException
{
CharStack s = new CharStack(10);
int i;
while ( (i = System.in.read()) != -1 )
{
s.push((char) i);
}
while (s.hasMoreElements())
{
System.out.write(s.pop());
}
System.out.println();
}
}
When I run this in Windows CLI I get:
C:\user>java CharStack
12345
54321