-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack2.java
More file actions
103 lines (97 loc) · 2.16 KB
/
Copy pathStack2.java
File metadata and controls
103 lines (97 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import java.util.Scanner;
public class Stack2 {
int cap,top,stud[];
Stack2(int max) //Parameterized Constructor
{
top=-1;
cap=max;
stud=new int[cap];
}
public void push(int n) throws OverflowException //Function to push values in stack
{
if(top==cap-1)
throw new OverflowException();
else
stud[++top]=n;
}
public int pop() throws UnderflowException //Function to pop values from stack
{
int k=-999;
if(top<0)
throw new UnderflowException();
else
k=stud[top--];
return k;
}
public void display() throws UnderflowException //Display function
{
int k;
if(top<0)
throw new UnderflowException();
else
{
for(k=top;k>=0;k--)
System.out.println(stud[k]);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of stack");
int s=sc.nextInt();
Stack2 ob=new Stack2(s);
int ch=0;
while(1>0)
{
System.out.println("\nEnter the choice\n1 to push in stack\n2 to pop from stack\n3 to print stack\n4 to Exit Program");
ch=sc.nextInt();
switch(ch)
{
case 1:try {
System.out.println("Enter number to be pushed in stack");
int v=sc.nextInt();
ob.push(v);
break;
}
catch(OverflowException e)
{
System.out.println(e);
break;
}
case 2:try {
ob.pop();
break;
}
catch(UnderflowException e)
{
System.out.println(e);
break;
}
case 3:try {
ob.display();
break;
}
catch(UnderflowException e)
{
System.out.println(e);
break;
}
case 4:System.exit(0);
break;
default:System.out.println("Wrong,choice enterred");
}
}
}
}
class OverflowException extends Exception{
public String toString()
{
return "OVERFLOW";
}
}
class UnderflowException extends Exception{
public String toString()
{
return "UNDERFLOW";
}
}