-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParenthesesBalancedStack.java
58 lines (46 loc) · 1.03 KB
/
ParenthesesBalancedStack.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
// Jonathan Rumley
// CSC 161-101
// October 12th, 2020
// Exercise #6 - Are parentheses balanced? Using Stack
// Tracy Dobbs
//
import java.util.Scanner;
import java.util.Stack;
import java.io.File;
public class ParenthesesBalancedStack
{
public static void main(String[] args) throws Exception
{
Stack<Character> chStack = new Stack<>();
Scanner fileInput = new Scanner(new File("Parens.txt"));
String str = "";
boolean balanced = true;
while(fileInput.hasNext())
{
balanced = true;
str = fileInput.nextLine();
for(int x=0; x < str.length(); x++)
{
if(str.charAt(x) == '(')
chStack.push(str.charAt(x));
try
{
if(str.charAt(x) == ')')
chStack.pop();
}
catch(java.util.EmptyStackException ESE)
{
balanced = false;
}
}
if(!chStack.isEmpty())
{
balanced = false;
}
if(balanced)
System.out.println("Balanced");
else
System.out.println("Unbalanced");
}
}
}