Hey guys ive come stuck once again, I can manage to push items onto a stack and pop them off. I even got working a stack with open and close brackets. But when I come to do it with () or {} or [] brackets with my code I created it seems to ignore the if statement and goes to else any ideas why.
Main.java
public class DifferentBrackets {
public static void main(String[] args) {
Stack brackets = new Stack();
Scanner k = new Scanner(System.in);
System.out.println("* to Terminate or Enter bracket : ");
String tempBrack = k.next();
while (!tempBrack.equals("*")) {
System.out.println("* to Terminate or Enter bracket : ");
switch (tempBrack) {
case "(":
brackets.push("(");
System.out.println(tempBrack + " is added");
break;
case "{":
brackets.push("{");
System.out.println(tempBrack + " is added");
break;
case "[":
brackets.push("[");
System.out.println(tempBrack + " is added");
break;
case ")":
if (tempBrack.equals(brackets.arrayTop()))
{
System.out.println(brackets.pop() + " is popped");
}
else if(tempBrack.equals(brackets.arrayTop()))
{
System.out.println("Closed Bracket Doesnt Match Top Open Bracket");
}
else
{
System.out.println("Closed Bracket Doesnt Match Top Open Bracket");
}
break;
// case "}":
// if (tempBrack.equals(brackets.arrayTop()))
// {
// System.out.println(brackets.pop() + " is popped");
// }
// else if (!tempBrack.equals(brackets.arrayTop()))
// {
// System.out.println("Closed Bracket Doesnt Match Top Open Bracket");
// }
//
// break;
// case "]":
// if (tempBrack.equals(brackets.arrayTop()))
// {
// if (!tempBrack.equals(brackets.arrayTop()))
// {
// System.out.println("Closed Bracket Doesnt Match Top Open Bracket");
// }
// break;
}
System.out.println("* to Terminate or Enter bracket : ");
tempBrack = k.next();
}
}
}
Heres my Stack.java
import java.util.ArrayList;
public class Stack
{
private ArrayList<String> a;
public Stack()
{
a = new ArrayList(10); //initial capacity of 10
}
public boolean isEmpty()
{
return a.isEmpty();
}
public String pop() //pop integer element
{
String last;
last = a.remove((a.size()- 1));
return(last); //underflow will crash
}
public void push(String x) //push integer element
{
a.add(x);
}
public String arrayTop()
{
return(a.get(a.size() -1));
}
}
else ifis useless as it checkes the same condition as yourif