I am learning java and I have written a program on stack(LIFO). Aim of the code is to read integers from keyboard and build a stack.
class StackDemo
{
public static void main(String[] arg)
throws java.io.IOException{
Stack s1 = new Stack();
char ch1;
System.out.println("would you like to push data into stack??? Enter y for yes. Enter n for no");
ch1 = (char) System.in.read();
if(ch1 == 'y')
{
for(int i=0; i<10; i++)
{
int input;
System.out.println("Enter an integer to push to the stack");
input = (int)System.in.read();
s1.push(input);
}
}
else if(ch1 == 'n')
{
}
else
{
System.out.println("push - Enter a valid input");
}
}
}
When I run the program, following result is displayed on console.
----------------------------------------------------------------------------
D:\personal\learn_social\Java\Complete_reference\Programs>java StackDemo
would you like to push data into stack??? Enter y for yes. Enter n for no
y
Enter an integer to push to the stack
Value is pushed onto stack successfully
Enter an integer to push to the stack
Value is pushed onto stack successfully
Enter an integer to push to the stack
----------------------------------------------------------------------------
But Expected result is
-------------------------------------------------------------------------
D:\personal\learn_social\Java\Complete_reference\Programs>java StackDemo
would you like to push data into stack??? Enter y for yes. Enter n for no
y
Enter an integer to push to the stack
-------------------------------------------------------------------------
Can anyone help what is the problem in code?
Thanks in advance, Nikhil S
Value is pushed onto stack successfullyis printed so is there something missing?