-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.java
65 lines (60 loc) · 1.42 KB
/
main.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
58
59
60
61
62
63
64
import java.util.*;
public class PA4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack<Character> s= new Stack<Character>();
try (Scanner keyboard = new Scanner(System.in)) {
//input
System.out.print("Enter a math formula: ");
String input = keyboard.nextLine();
//algorithm
boolean balance = true;
char x = ' ';
int i = 0;
for( i = 0;i < input.length(); i++ ) {
x = input.charAt(i);
if (x == '(' || x== '[' || x=='{') {
s.push(x);
continue;
}else if(x ==')' ){
if( s.isEmpty()){
balance = false;
break;
}
char off = s.pop();
if (off != '(' ) {
balance = false;
break;
}
}else if(x ==']' ){
if( s.isEmpty() ) {
balance = false;
break;
}
char off = s.pop();
if(off != '['){
balance = false;
break;
}
}else if(x =='}'){
if( s.isEmpty() ){
balance = false;
break;
}
char off = s.pop();
if (off !='{') {
balance = false;
break;
}
}
}
if(balance == true && s.isEmpty()) {
System.out.println("The input expression is balanced!");
}
else {
System.out.println("The input expression is not balanced! The first mismatch is found at position "+(i)+"!");
}
keyboard.close();
}
}
}