错误:无法从静态上下文引用非静态方法

时间:2014-03-25 15:41:35

标签: java static stack non-static static-content

是的,我知道这个错误比普通流感更常见,而且我不知道如何修复它。因为坦率地说,我不知道这个特定实例意味着什么。我有非常简单的代码来检查括号,但是它没有编译,因为这个,我不知道为什么。

错误发生在第14行的测试类中。

但这是我的两个也是唯一的课程。

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


}

有错误的那个:

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

2 个答案:

答案 0 :(得分:4)

在示例中查看以下几行:

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

第一行创建一个对象。它使用算术类并调用带字符串的构造函数。然后,由于没有为结果分配变量,新对象将被丢弃。

第二行尝试调用isBalanced。但是(因为它没有用static声明)isBalanced是一个实例方法,这意味着它需要在算术实例上调用。您创建了一个可以在上一行中调用isBalanced的对象,您只需要保留对它的引用,并使用该引用。

将新对象分配给变量:

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

答案 1 :(得分:0)

问题是您在课程isBalanced上拨打Arithmetic,而不是在实例上。

以下内容应解决问题:

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

作为旁注:Boolean是设置boolean值的类的名称。

相关问题