【发布时间】:2014-02-17 21:00:40
【问题描述】:
到目前为止,我有以下代码:
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() 方法也静态,但是我的教授告诉我不要使该字段静态。有没有我只是想念的简单解决方案?
【问题讨论】:
-
but I was told not to make that field static by my professor因此,替代方案是......? -
有关静态引用和非静态成员的信息,请查看本页右侧“相关”下的内容。
-
创建一个实例。我有点喜欢把它命名为
me:MyClass me = new MyClass(); double value = me.getCurrentValue(); -
@user3221816 - 在任何人为您回答这个问题之前,他们需要知道 - 您知道“静态”的实际含义吗?如果你这样做,答案应该是显而易见的。如果您不这样做,那么我建议您阅读您的课程笔记或在线 Java 教程。
-
我同意@DavidWallace。创建一个实例并使用该对象从静态上下文访问非静态方法或变量。
HallLanceMemoryCalculator c = new HallLanceMemoryCalculator(); double value=c.getCurrentValue();
标签: java static-methods