非静态变量不能从静态引用 [英] non-static variable cannot be referenced from a static

查看:114
本文介绍了非静态变量不能从静态引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们
我编写了此程序
但第127行出现错误,提示:
非静态变量不能从静态引用
我该怎么办?!!:((

/////

hi guys
i coded this program
but there is an error in line 127 that is saying:
non-static variable cannot be referenced from a static
what should i do ?!!:((

/////

package itp2;
import java.util.*;
import java.io.*;
class StackX
{
private int maxSize;
private char[] stackArray;
private int[] stackArray1;
private int top;
 
public StackX(int s)
{
maxSize = s;
stackArray = new char[maxSize];
top = -1;
}
 
public void push(char j)
{ stackArray[++top] = j; }
 
public void push1(int j)
{ stackArray1[++top] =j ; }
 
public char pop()
{ return stackArray[top--]; }
public int pop1()
{ return stackArray[top--]; }
public char peek()
{ return stackArray[top]; }
 
public boolean isEmpty()
{ return (top == -1); }
 
public int size()
{ return top+1; }
 
public char peekN(int n)
{ return stackArray[n]; }
 
 
 
} // end class StackX used from lab1
 
class InToPost // infix to postfix conversion borrowed from book
{
private StackX theStack;
private String input;
private String output = "";
 
public InToPost(String in) // constructor
{
input = in;
int stackSize = input.length();
theStack = new StackX(stackSize);
}
 
public String doTrans() // algorithm that does translation with cases
{
for(int j=0; j<input.length(); j++)
{
char ch = input.charAt(j);
 
switch(ch)
{case '+':gotOper(ch, 1); break;
case '-':gotOper(ch, 1); break;
case '*':gotOper(ch, 2); break;
case '/':gotOper(ch, 2); break;
default :output = output + ch; break; //writes to output
} // end of switch
} // end for loop
while( !theStack.isEmpty() ) // pop remaining operators at the end
{
output = output + theStack.pop(); // write to output
}
return output; // return postfix
}
//--------------------------------------------------------------
public void gotOper(char opThis, int prec1)
{
while( !theStack.isEmpty() )
{
char opTop = theStack.pop();
 
if(1==1 )
{
int prec2;
 
if(opTop=='+' || opTop=='-') // find new op prec
prec2 = 1;
else
prec2 = 2;
if(prec2 < prec1)
{
theStack.push(opTop);
break;
}
else
output = output + opTop;
}
} // end while loop
theStack.push(opThis);
}
}


 
 

public class ITP2 {
 
public static void main(String[] args) throws IOException
{
String output;
String input;
while(true)
{
System.out.print("Enter infix: ");
System.out.flush();
input = getString();
if( input.equals("") )
break;
 
InToPost theTrans = new InToPost(input);
output = theTrans.doTrans();
//Eval x=new Eval();
 System.out.println("Evaluated expression: " + (output));
 System.out.println("Postfix is " + evaluate(output)) ;//// line 127
}
}
 
   class Eval{
private StackX operatorStack ;
private StackX operandStack;
private String output;
Eval (){
    
}
public int evaluate( String output)
{
StringTokenizer s = new StringTokenizer(output);//divides into tokens
 
int value;
String symbol;
while (s.hasMoreTokens())
{
symbol = s.nextToken();
if (Character.isDigit(symbol.charAt(0)))// if its a number push it
 
{
Integer operand = new Integer(Integer.parseInt(symbol));
operandStack.push1(operand);
}
else // if it's an operator, operate on the previous two popped operandStack items
{
int op2 = ((Integer)operandStack.pop1()).intValue();
int op1 = ((Integer)operandStack.pop1()).intValue();
int result = 0;
switch(symbol.charAt(0))
{
case '*': {result = op1 * op2; break;}
case '+': {result = op1 + op2; break;}
case '-': {result = op1 - op2; break;}
case '/': {result = op1 / op2; break;}
case '%': {result = op1 % op2; break;}
}
Integer operand = new Integer(result);
operandStack.push1(operand);
}
}
value = ((Integer)operandStack.pop1()).intValue();
return value;
}
 
}



 public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}

    
}

推荐答案

从静态函数main调用非静态函数evaluate时会发生问题. 所有您需要做的就是使您的评估函数也保持静态. public static int evaluate( String output)

静态和非静态之间的区别在于,您可以使用静态函数而不必创建类的实例.例如,使用BufferedReader才能使用readLine函数,您需要创建该类的new实例,而使用静态函数时,您只能调用它:
StackX.evaluate(...)不必执行StackX myStack = new StackX(); myStack.evaluate(...)



对不起,我认为评估函数与主要函数在同一个类中.确保代码格式正确的另一个极好的原因.
就像Philippe Mori提到的那样,在第125行中,您已经注释掉了我怀疑您可能需要的代码.您应该取消注释,并使用x.evaluate(...)
The problem occurs when you call the non-static function evaluate from the static function main. All you should have to do is make your evaluate function static as well. public static int evaluate( String output)

The difference between static and non-static is that you can use the static functions without having to make an instance of the class. With the BufferedReader for example before you can use the readLine function you need to make a new instance of the class, whereas with a static function you can just call it:
StackX.evaluate(...) instead of having to do StackX myStack = new StackX(); myStack.evaluate(...)



Sorry I thought the evaluate function was in the same class as the main function. Another excellent reason for making sure you code is correctly formatted.

Like Philippe Mori mentioned, on line 125 you''ve commented out the code I suspect you might need. You should uncomment that and use x.evaluate(...)


附加注释,格式化代码!情况越混乱,您犯的错误就越多.

学会在每个块上都套上括号.在ifwhilecasefor块中,很容易出错,如果您始终撑一下,即使是一行,您以后也可以避免头痛.
避免将多个命令放在一行上:
An additional comments, format your code! The messier it is, the more mistakes you''ll make.

Learn to put braces around EVERY block. In if, while, case and for blocks it is so easy to get this wrong, if you always brace, even for one line, you''ll prevent a headache later.
Avoid putting multiple commands on a single line:
// vile and ugly:
case '+':gotOper(ch, 1); break;

// readable and clear
case '+': {
    gotOper(ch, 1);
    break;
}



请注意,在该块开头的行末尾有括号,而不是在下一行.
如果使用正确的IDE(Netbeans或Eclipse),则可以将其设置为自动提供花括号.我建议你这样做.

另一个好的做法是在编写方法之前自由使用JavaDoc注释并编写它们.这是一个好习惯,因为您必须用英语(或您喜欢的任何一种)编写,然后在添加任何代码之前该方法将执行的操作.编写代码后,然后检查JavaDoc是否正确.

您的代码,已格式化并正确加括号:



Notice the brace at the end of the line beginning the block, not on the next line.
If you use a proper IDE - Netbeans or Eclipse - you can set it to automatically provide the braces. I suggest you do so.

Another good practice is to use JavaDoc comments liberally and to write them BEFORE you write the method. This is good practice as you must write in English - or whatever you prefer - what the method will do before you add any code. After writing the code, then check that the JavaDoc is correct.

Your code, formatted and properly braced:

package itp2;
import java.util.*;
import java.io.*;
class StackX {
    private int maxSize;
    private char[] stackArray;
    private int[] stackArray1;
    private int top;
     
    public StackX(int s) {
        maxSize = s;
        stackArray = new char[maxSize];
        top = -1;
    }
     
    public void push(char j) {
        stackArray[++top] = j;
    }
     
    public void push1(int j) {
        stackArray1[++top] =j;
    }
     
    public char pop() {
        return stackArray[top--];
    }
    
    public int pop1() {
        return stackArray[top--];
    }
    
    public char peek() {
        return stackArray[top];
    }
     
    public boolean isEmpty() {
        return (top == -1);
    }
     
    public int size() {
        return top+1;
    }
     
    public char peekN(int n) {
        return stackArray[n];
    }
     
     
 
} // end class StackX used from lab1
 
/** infix to postfix conversion borrowed from book */
class InToPost {
    private StackX theStack;
    private String input;
    private String output = "";
    
    /** constructor */
    public InToPost(String in) {
        input = in;
        int stackSize = input.length();
        theStack = new StackX(stackSize);
    }
    
    /** algorithm that does translation with cases */
    public String doTrans() {
        for(int j=0; j<input.length(); j++) {
        char ch = input.charAt(j);
         
            switch(ch) {
                case '+': {
                    gotOper(ch, 1);
                    break;
                }
                case '-': {
                    gotOper(ch, 1);
                    break;
                }
                case '*': {
                    gotOper(ch, 2);
                    break;
                }
                case '/': {
                    gotOper(ch, 2);
                    break;
                }
                default : {
                    output = output + ch;
                    break; //writes to output
                }
            } // end of switch
        } // end for loop
        // pop remaining operators at the end
        while( !theStack.isEmpty() ) 
        {
            output = output + theStack.pop(); // write to output
        }
        return output; // return postfix
    }
    
    /**--------------------------------------------------------------*/
    public void gotOper(char opThis, int prec1)
    {
        while (!theStack.isEmpty()) {
            char opTop = theStack.pop();
             
            if(1==1 ) {
                int prec2;
                
                // find new op prec
                if (opTop=='+' || opTop=='-') {
                    prec2 = 1;
                } else {
                    prec2 = 2;
                }
                if(prec2 < prec1) {
                    theStack.push(opTop);
                    break;
                } else {
                    output = output + opTop;
                }
            }
        } // end while loop
        theStack.push(opThis);
    }
}

public class ITP2 {
     
    public static void main(String[] args)
            throws IOException {
        String output;
        String input;
        while(true) {
            System.out.print("Enter infix: ");
            System.out.flush();
            input = getString();
            if( input.equals("") ) {
                break;
            }
         
            InToPost theTrans = new InToPost(input);
            output = theTrans.doTrans();
            //Eval x=new Eval();
             System.out.println("Evaluated expression: " + (output));
             System.out.println("Postfix is " + evaluate(output)) ;//// line 127
        }
    }

    public static String getString()
            throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        String s = br.readLine();
        return s;
    }
    
    class Eval {
        private StackX operatorStack ;
        private StackX operandStack;
        private String output;
        Eval () {
        }

        public int evaluate( String output) {
            StringTokenizer s = new StringTokenizer(output);//divides into tokens
             
            int value;
            String symbol;
            while (s.hasMoreTokens()) {
                symbol = s.nextToken();
                // if its a number push it
                // if it's an operator, operate on the previous two popped operandStack items
                if (Character.isDigit(symbol.charAt(0))) {
                    Integer operand = new Integer(Integer.parseInt(symbol));
                    operandStack.push1(operand);
                } else {
                    int op2 = ((Integer)operandStack.pop1()).intValue();
                    int op1 = ((Integer)operandStack.pop1()).intValue();
                    int result = 0;
                    switch(symbol.charAt(0)) {
                        case '*': {
                            result = op1 * op2;
                            break;
                        }
                        case '+': {
                            result = op1 + op2;
                            break;
                        }
                        case '-': {
                            result = op1 - op2;
                            break;
                        }
                        case '/': {
                            result = op1 / op2;
                            break;
                        }
                        case '%': {
                            result = op1 % op2;
                            break;
                        }
                    }
                    Integer operand = new Integer(result);
                    operandStack.push1(operand);
                }
            }
            value = ((Integer)operandStack.pop1()).intValue();
            return value;
        }
         
    }        
}


这篇关于非静态变量不能从静态引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆