-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExceptionTest.java
More file actions
69 lines (67 loc) · 2.35 KB
/
Copy pathExceptionTest.java
File metadata and controls
69 lines (67 loc) · 2.35 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
import java.util.*;
public class ExceptionTest{
public static void main(String[] args){
String[] arr = {"a", "1", "+", "1", "$"};
Stack<Integer> stack = new Stack<>();
Set<String> set = new HashSet<>();
set.add("+");
set.add("-");
set.add("*");
set.add("/");
set.add("$");
for(String c : arr){
if(stack.isEmpty()){
if(!set.contains(c))
// Runtime exception no need to be threw explicitly
// but we can still use try... catch.
//try{
stack.push(Integer.valueOf(c));
//}catch(NumberFormatException ne){
// System.out.println("^^^^^^^^^^^^ ");
// ne.printStackTrace();
// System.out.println("## " + ne.toString());
//}
else
System.out.println("first char cannot be sign");
}else{
if(!set.contains(c))
try{
stack.push(Integer.valueOf(c));
}catch(NumberFormatException ne){
ne.printStackTrace();
System.out.println("## " + ne.toString());
}
else{
int a = stack.pop();
int b = stack.pop();
try{
stack.push(cal(a, b, c));
}catch(ArithmeticException ae){
ae.printStackTrace();
System.out.println("## " + ae.toString());
}catch(Exception e){
e.printStackTrace();
System.out.println("## " + e.toString());
}
}
}
}
System.out.println(stack.pop());
}
public static int cal(int a, int b, String c) throws Exception{
int ans = -666;
if(c.equals("+")){
ans = a + b;
}else if(c.equals("-")){
ans = b - a;
}else if(c.equals("*")){
ans = a * b;
}else if(c.equals("/")){
ans = b / a;
}else{
System.out.println("sign is error");
throw new Exception("error sign");
}
return ans;
}
}