Question

Yes, I know this error is more common than a the common flu, and no I have no idea how to fix it. Because quite frankly I have no idea what it means on this particular instance. I have very simple code to check for Parentheses but well its not compiling due this, and I am not sure why.

The error is in the test class, line 14.

But here are my two and only classes.

import java.util.Stack;
import java.util.EmptyStackException;

class Arithmetic
{

Stack <Object>stk;
String expression;
int length;

Arithmetic(String s) 
{
expression = s;
length = expression.length();
stk = new Stack<Object>();
}

boolean isBalanced()
{
int index = 0;
boolean fail = false;

try
  {
  while(index < length)
  {
  char ch = expression.charAt(index);

  switch(ch)
        {
        case '(':
                 stk.push(ch);
        break;

        case ')':
                 stk.pop();   
        break;

        default:
                 //ignore all others chars.
        break;               
        }
        index++; //increment index to continue on to the next char.
  }           

  }
  catch(EmptyStackException e)
  {
     fail = true;
  }
  return fail;
}


}

the one with the error:

 import javax.swing.JOptionPane;
 import javax.swing.JTextArea;

 class TestFile
 {
public static void main(String[] arg)
{

  String menu = "Please enter an arithmetic expression to evaluate for balance:";
  String s = JOptionPane.showInputDialog( menu);   
  display(s);

  new Arithmetic(s);
  boolean balanced = Arithmetic.isBalanced();

  display(balanced);


  }
  static void display(boolean Boolean)
{
    JOptionPane.showMessageDialog(null, Boolean, "Content",      JOptionPane.INFORMATION_MESSAGE);
}



static void display(String s)
{
    JOptionPane.showMessageDialog(null, s, "Content", JOptionPane.INFORMATION_MESSAGE);
}
 }
Was it helpful?

Solution

Look at these lines in your example:

new Arithmetic(s);
boolean balanced = Arithmetic.isBalanced();

The first line creates an object. It uses the class Arithmetic and invokes the constructor that takes a string. Then, since no variable gets assigned the result, the new object gets thrown away.

The second line tries to call isBalanced. But (because it isn't declared with static) isBalanced is an instance method, that means it needs to be called on an instance of Arithmetic. You made an object that you could call isBalanced on in the previous line, you just need to keep a reference to it, and use that reference.

Assign the new object to a variable:

Arithmetic a = new Arithmetic(s);
boolean balanced = a.isBalanced();

OTHER TIPS

The problem is that you call isBalanced on the class Arithmetic, not on an instance.

The following should fix the problem:

Arithmetic a = new Arithmetic(s);
a.isBalanced();

As a side note: Boolean is the name of a class that boxes a boolean value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top