gpt4 book ai didi

java - 如何从另一个类中的另一个公共(public)整数调用公共(public)整数?

转载 作者:行者123 更新时间:2023-12-02 01:16:18 31 4
gpt4 key购买 nike

我正在为类(class)做一项作业,它正在处理类(class),以使我们尽可能频繁地调用其他类(class)的项目。我试图从另一个 public int 调用 public int side(int number),但它不允许我这样做。

我根本无法重新排列代码来编辑 public int 端,因为它包含在作业的一部分中

package lab6_carl6188;

class Polygon
{
private int[] sideLengths;

public Polygon(int sides, int ... lengths)
{
int index = 0;
sideLengths = new int[sides];
for (int length: lengths)
{
sideLengths[index] = length;
index += 1;
}
}

public int side(int number)
{
return sideLengths[number];
}

public int perimeter()
{
int total = 0;
for (int index = 0; index < sideLengths.length; index += 1)
{
total += side(index);
}
return total;
}
}

class Rectangle{
private int[] sideLengths;
public Rectangle(int length1, int length2) {
sideLengths[0] = length1;
sideLengths[1] = length2;
}
public int area() {
int total = 1;
for(int x = 0; x < sideLengths.length; x++) {
total = total * Polygon.side(x);
}
}

}

}

这整个 block 就是代码。我不允许以任何方式编辑 Polygon 类。

public int side(int number) 
{
return sideLengths[number];
}

是我想调用的,我这样调用它:

public int area() {
int total = 1;
for(int x = 0; x < sideLengths.length; x++) {
total = total * Polygon.side(x);
}
}

我的错误是“无法从 Polygon 类型对非静态方法 side(int) 进行静态引用”

最佳答案

Polygon.side 不是静态方法。这意味着您不能在类对象上调用它,而是需要创建该类的实例。

Polygon polygon = new Polygon();
polygon.side(x);

关于java - 如何从另一个类中的另一个公共(public)整数调用公共(public)整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58494927/

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