-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackOverUnderFlowExceptions.java
57 lines (52 loc) · 1.46 KB
/
StackOverUnderFlowExceptions.java
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
import java.util.Scanner;
class StackOverFlowException extends Exception {
public String toString(){
return "StackOverFlowException: Stack Overflow";
}
}
class StackUnderFlowException extends Exception {
public String toString(){
return "StackUnderFlowException: Stack Underflow";
}
}
class Stack {
int top = -1;
int size;
int[] arr;
Stack() {
arr = new int[size];
}
void push(int data) throws StackOverFlowException {
if (top == size - 1) {
throw new StackOverFlowException();
}
arr[++top] = data;
}
int pop() throws StackUnderFlowException {
if (top == -1) {
throw new StackUnderFlowException();
}
return arr[top--];
}
}
public class StackOverUnderFlowExceptions {
public static void main(String[] args) {
Stack s = new Stack();
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of stack: ");
int size = sc.nextInt();
try{
for(int i=0;i<size;i++){
System.out.println("Enter data: ");
int data = sc.nextInt();
s.push(data);
}
for(int i=0;i<size;i++){
System.out.println(s.pop());
}
}
catch(StackOverFlowException | StackUnderFlowException e){
System.out.println(e);
}
}
}