I learn stacks by writing a program that checks the syntax of brackets. If I introduce (Baller), it should give me a positive result. If I have (Baller(), this should give me a negative result. Essentially, the application verifies the correct use of the user (), {} and [].
- If I come across a character (, {, or [], I will add it to the character on the stack.
- If I come across the a)}] sign, I will remove the character from the stack.
- If the text contains an odd number of brackets or parentheses (for example, (and] is not continuous), an error message is printed.
So, I did this half in the if else statement, but I thought it should be easier to do in the switch statement, and also be a good learning experience.
So what I did in the switch statement:
public class Input {
public static void main(String[] args) {
Stack stack = new Stack();
String str;
str = JOptionPane.showInputDialog("Text to parse: ");
char arr[] = str.toCharArray();
System.out.print(str);
System.out.println();
System.out.println();
for(char c : arr) {
switch(c) {
case '{':
stack.Push(c);
System.out.print(stack.firstNode.getData());
break;
case '(':
stack.Push(c);
System.out.print(stack.firstNode.getData());
break;
case '[':
stack.Push(c);
System.out.print(stack.firstNode.getData());
break;
case '}':
c = (Character) stack.Peek();
if( c != '{') {
System.out.println(" Syntax ERROR");
}
case ']':
if( c != '[') {
System.out.println(" Syntax ERROR");
}
case ')':
if( c != '(') {
System.out.println(" Syntax ERROR");
}
}
}
}
}
: , , . if-else, if-, :
if(first == '(' && (current == '}' || current == ']')) {
if first == '{' && (current == ']' || current == ')')) {
//and so on
? ?
, , .
:
import javax.swing.JOptionPane;
public class Input {
public static void main(String[] args) {
Stack stack = new Stack();
String str;
str = JOptionPane.showInputDialog("Text to parse: ");
char arr[] = str.toCharArray();
System.out.print(str);
System.out.println();
System.out.println();
for(char c : arr) {
switch(c) {
case '{':
stack.Push(c);
break;
case '(':
stack.Push(c);
break;
case '[':
stack.Push(c);
break;
case '}':
if(stack.isEmpty() || (Character) stack.Pop() != '{') {
System.out.println(" Syntax ERROR");
}
break;
case ']':
if(stack.isEmpty() || (Character) stack.Pop() != '[') {
System.out.println(" Syntax ERROR");
}
break;
case ')':
if(stack.isEmpty() || (Character) stack.Pop() != '(') {
System.out.println(" Syntax ERROR");
}
break;
}
} if(!stack.isEmpty()) {
System.out.println(" Syntax ERROR");
}
}
}