无法对非静态方法进行静态引用 [英] cannot make a static reference to a non static method
问题描述
到目前为止,我有以下代码:
So far I have the following code:
import java.util.Scanner;
public class HallLanceMemoryCalculator {
private double currentValue;
public static int displayMenu(){
Scanner input=new Scanner(System.in);
int choice=0;
while(choice<1||choice>5){
System.out.println("1.Add");
System.out.println("2.Subtract");
System.out.println("3.Multiply");
System.out.println("4.Divide");
System.out.println("5.Clear");
System.out.println("What would you like to do?");
choice=input.nextInt();
}
return choice;
}
public static double getOperand(String prompt){
Scanner input=new Scanner(System.in);
System.out.println("What is the second number?");
double secondNumber=input.nextDouble();
return secondNumber;
}
public double getCurrentValue(){
return currentValue;
}
public void add(double operand2){
currentValue+=operand2;
}
public void subtract(double operand2){
currentValue-=operand2;
}
public void multiply(double operand2){
currentValue*=operand2;
}
public void divide(double operand2){
currentValue/=operand2;
}
public void clear(){
currentValue=0;
}
public static void main(String[] args) {
double value=getCurrentValue();
}
}
当我尝试在最后设置double value = getCurrentValue();
时,我收到一条错误消息无法对非静态方法进行静态引用。它说修复是使 getCurrentValue()
方法也是静态的,但我被告知不要让我的教授将该字段设为静态。有没有一个简单的解决方案,我只是缺少?
When I try to set double value=getCurrentValue();
at the end, I get an error message "Cannot make a static reference to the non-static method." It says the fix is to make the getCurrentValue()
method static as well, but I was told not to make that field static by my professor. Is there a simple solution to this that I am just missing?
推荐答案
静态方法属于类,非静态方法属于该类的实例。
A static method belongs to the class, a non-static method belongs to an instance of the class.
当您调用 getCurrentValue()
时从 main
,您收到错误,因为 main
与任何实例都没有关联。
When you call getCurrentValue()
from main
, you get an error because main
isn't associated with any instance.
你需要创建一个类的实例:
You need to create an instance of the class:
HallLanceMemoryCalculator me = new HallLanceMemoryCalculator();
然后你可以调用实例的 getCurrentValue()
:
Then you can call the instance's getCurrentValue()
:
double value = me.getCurrentValue();
这篇关于无法对非静态方法进行静态引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!