gpt4 book ai didi

java - 如何从静态上下文引用非静态方法

转载 作者:行者123 更新时间:2023-12-02 05:30:36 25 4
gpt4 key购买 nike

我有一个带有函数的构造函数,但是当我编译我的主方法时,我无法从静态上下文引用非静态方法区域。我知道这是一个简单的修复,但我只是无法完全到达那里。谢谢

public class Rect{
private double x, y, width, height;

public Rect (double x1, double newY, double newWIDTH, double newHEIGHT){
x = x1;
y = newY;
width = newWIDTH;
height = newHEIGHT;

}
public double area(){
return (double) (height * width);
}

以及这个主要方法

public class TestRect{

public static void main(String[] args){
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
double height = Double.parseDouble(args[2]);
double width = Double.parseDouble(args[3]);
Rect rect = new Rect (x, y, height, width);
double area = Rect.area();

}
}

最佳答案

您需要在类的实例上调用该方法。

这段代码:

Rect rect = new Rect (x, y, height, width);
double area = Rect.area();

应该是:

Rect rect = new Rect (x, y, height, width);
double area = rect.area();
^ check here
you use rect variable, not Rect class
Java is Case Sensitive

关于java - 如何从静态上下文引用非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25589961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com