1

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();
}

}

Leslie
  • 51
  • 6

1 Answers1

1

Your problem is probably in one of the lines of code you didn't show. I can't tell for sure without that code.

Since you use a variable "s", but never declare it in the code you've shown, I assume it's declared in your class, and that it's not static. Therefore, you can't use that variable in your static methods (which they all seem to be).

Either make that variable static (which seems to be what you're doing for everything), or you'll need to figure out how to instantiate your class from your main method.

That may fix the issue, but you might have more... again, I can't tell without all the code.

billjamesdev
  • 14,554
  • 6
  • 53
  • 76