$24
Using java.util.Stack – don’t write your own stack class – write two programs corresponding to the algorithms described in class.
Use the class names prescribed. Do not put classes in a package. Make sure your code behaves as described.
Program 1
Name this class Balanced.
Repeatedly read a line from System.in and print out either balanced or imbalanced depending on whether or not the delimiters are balanced.
Do not print anything else. I will be grading this assignment with an automated script.
Exit the program when the user enters a blank line.
Read in the line and iterate over the characters like so:
String line = input.nextLine(); // input is the Scanner
for (int i=0; i<line.length(); i++)
{
char c = line.charAt(i);
// do something with c
}
Program 2
Name this class Postfix.
1
Read a line from System.in representing a postfix expression. Evaluate the expression and print out the numeric result, or Error if the expression is invalid. Use double for all numeric types.
Do not print anything else. I will be grading this assignment with an automated script.
Exit the program when the user enters a blank line.
All symbols will be separated by spaces. Process the input with a loop like so:
String line = input.nextLine(); // input is the Scanner
TODO: make sure to check for blank lines...
this scanner will break line into words Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNext())
{
if (lineScanner.hasNextDouble())
{
double d = lineScanner.nextDouble();
// process the number
}
else
{
String operator = lineScanner.next();
// process the operator
}
}
Turn in
The two java files. Make sure to put your name in comments at the top of every source code file.
Code must compile to be worth any points.
2