-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedStack
More file actions
91 lines (73 loc) · 2.91 KB
/
BalancedStack
File metadata and controls
91 lines (73 loc) · 2.91 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
/*
* Jeanine Rioux
* CSC 18 C
* Assignment #4: Stacks
*
* Instructions: Fill out your name under programmer name, the date and time you started the assignment,
the date and time you completed the assignment, total hours you dedicated to the assignment (should be
a minimum of 1 1/2 hours for a good quality, well done assignment - rules of academic honesty apply for
this), and any constructive comments you have about the assignment (could be things you liked about the
assignment; or if you had the opportunity to do the assignment all over again, what would you do
differently?)
Programmer Name: Jeanine Rioux
Assignment Start: 4/30/18 (1 hr 30 min)
Assignment Completion: 5/2/18 (20 min)
Total Hours for Assignment: 1 hr 50 min
Comments: This gave me an opportunity to implement try/catch, which was not something I was comfortable using
I considered using switch/case and it might be fun to revisit it that way to see if it looks more elegant.
*/
package asmt4_stacks_balanced;
import java.util.Scanner;
import java.lang.NullPointerException;
public class Asmt4_Stacks_Balanced {
public static void main(String[] args) {
String expression = new String();
boolean check;
Scanner kb = new Scanner(System.in);
System.out.println("Enter an expression to determine if it is balanced.");
expression = kb.nextLine();
check = checkIsBalanced(expression);
System.out.println(check);
}// end method main
public static boolean checkIsBalanced(String expr)
{
char[] temp = expr.toCharArray();
Stack <Character> braces = new Stack<Character>();
try
{
for (int i=0; i<temp.length; i++)
{
if (temp[i] == '(' || temp[i] == '[' || temp[i] == '{')
braces.push(temp[i]);
else if (temp[i]== ')')
{
if (braces.peek() == '(')
braces.pop();
else
return false;
}// end else if )
else if (temp[i]== ']')
{
if (braces.peek() == '[')
braces.pop();
else
return false;
}// end else if ]
else if (temp[i]== '}')
{
if (braces.peek() == '{')
braces.pop();
else
return false;
}// end else if }
}// end for loop
if(braces.pop()!= null)
return false;
return true;
}// end try block
catch(NullPointerException nullPointerException)
{
return false;
}//end catch block
}// end method checkIsBalanced
}//end class implementing a Balanced Stack