Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

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

}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A static method belongs to the class, a non-static method belongs to an instance of the class.

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

Then you can call the instance's getCurrentValue():

double value = me.getCurrentValue();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...