In the do-while loop,the code is not taking input after first case. it gets terminated after taking the input and does not performs do-while loop properly.what is wrong with z=sc.nextLine(){in the while loop} or Scanner class ? PS: I also tried with Scanner sc=new Scanner("System.in"); but the code still didn't work. Any other alternative than parseInt() ?
OUTPUT COMING : size of stack? 5 1.PUSH 2.POP 3.Display 1 number for push? 19 continue? after continue,code gets terminated
Please Help.
class stak{
int tos=-1;
int size;
int a[];
stak(int l){
size=l;
tos=-1;
a=new int[l];
}
void push(int x){
if(tos==size-1){
System.out.println("Stack Overflow");
}
else{
a[++tos]=x;
}
}
void pop(){
if(tos<0){
System.out.println("Stack Underflow");
}
else{
System.out.println(a[tos--]);
}
}
void display(){
if(tos>=0){
for(int i=tos;i>=0;--i){
System.out.println(a[i]);
}
}
else
System.out.println("Stack is Empty");
}
}
public class stack{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("size of stack?");
int n=sc.nextInt();
stak s1=new stak(n);
String z;
do{
System.out.println("1.PUSH");
System.out.println("2.POP");
System.out.println("3.Display");
int ch=sc.nextInt();
switch(ch){
case 1 : System.out.println("number for push?");
int p=sc.nextInt();
s1.push(p);
break;
case 2 : System.out.println("POP!");
s1.pop();
break;
case 3 : System.out.println("Display!");
s1.display();
break;
default: System.out.println(" OOPS! owner says only take input as: 1,2,3");
break;
}
System.out.println("continue?");
z=sc.nextLine();
}while(z.equals("yes")|| z.equals("y"));
sc.close();
}
}
[1]: https://i.stack.imgur.com/BHZQO.png