Hi,i wrote code for stack operations.
I pasted that code below,
import java.io.*;
class Stack
{
int i;
int[] st;
public Stack(int size)
{
st=new int[size];
i=-1;
}
public void push()throws IOException
{
i++;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a element:");
st[i]=Integer.parseInt(br.readLine());
}
public void pop()
{
if(i<0)
System.out.println("Stack is empty.");
else
{
i--;
System.out.print("Last entered number is deleted.");
}
}
public void checkempty()
{
if(i<0)
System.out.println("Stack is empty.");
else
System.out.println("Stack is not empty.");
}
public void noofelements()
{
System.out.println("Number of elements in the Stack :"+(i+1));
}
public void printelements()
{
if(i<0)
System.out.println("Stack is empty.");
else
{
System.out.println("Stack elements are :");
for(int j=0;j<=i;j++)
System.out.println(st[i]+" ");
}
}
}
class StackOperations
{
public static void main(String[] args)throws IOException
{
int a,size;
String check;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the length of the stack:");
size=Integer.parseInt(br.readLine());
Stack stobject=new Stack(size);
System.out.println("This program is to perform stack operations.\n");
System.out.println("Options for each operation;");
System.out.println("1.insertion.");
System.out.println("2.deletion.");
System.out.println("3.to check stack is empty or not.");
System.out.println("4.to print number of elements in stack.");
System.out.println("5.to print stack elements.");
do
{
System.out.print("\nEnter Your option:");
a=Integer.parseInt(br.readLine());
System.out.print("\n");
switch(a)
{
case 1: //insertion.
{
stobject.push();break;
}
case 2: //deletion.
{
stobject.pop();break;
}
case 3: //check empty.
{
stobject.checkempty();break;
}
case 4: //stack elements number.
{
stobject.noofelements();break;
}
case 5: //to print stack elements.
{
stobject.printelements();break;
}
}
System.out.print("\nDo you want to continue(Enter yes/no) :");
check=br.readLine();
}while(check=="yes");
}
}
With the above program i didn't get any errors.
But even though i entered yes for checking do-while loop,it comes out of the loop.
Is there any mistake in my code ?
And was i followed correct way to insertion, deletion and also for all other methods ?