I'm making a program that checks whether braces are balanced in another program, and I'm having trouble with static vs. non-static variables. It says I cannot reference my non-static Stack from a static context, but I'm reading for a file, so I have to change the Stack. Any suggestions? Thanks!
public static void main(String[] args)
{
readFile();
if(isBalanced() == true)
System.out.println("program is balanced");
else
System.out.println("program is not balanced");
}
private static void readFile()
{
try
{
Scanner fin = new Scanner(new File("test.txt"));
while(fin.hasNext())
{
s.add(fin.nextLine());
System.out.println("");
}
}catch(IOException ex)
{
System.out.println("File Not Found");
}
}
public static boolean isBalanced()
{
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++)
{
if(s.charAt(i) == LEFT_PARENT)
stack.push(LEFT_PARENT);
else if(s.charAt(i) == LEFT_BRACE)
stack.push(LEFT_BRACE);
else if(s.charAt(i) == LEFT_BRACKET)
stack.push(LEFT_BRACKET);
else if(s.charAt(i) == LEFT_POINT)
stack.push(LEFT_POINT);
else if(s.charAt(i) == RIGHT_PARENT)
{
if(stack.isEmpty())
return false;
if(stack.pop() != LEFT_PARENT)
return false;
}
else if(s.charAt(i) == RIGHT_BRACE)
{
if(stack.isEmpty())
return false;
if(stack.pop() != LEFT_BRACE)
return false;
}
else if(s.charAt(i) == RIGHT_BRACKET)
{
if(stack.isEmpty())
return false;
if(stack.pop() != LEFT_BRACKET)
return false;
}
else if(s.charAt(i) == RIGHT_POINT)
{
if(stack.isEmpty())
return false;
if(stack.pop() != LEFT_POINT)
return false;
}
}
return stack.isEmpty();
}
}