gpt4 book ai didi

java - "Cannot find symbol"- 具有 main 方法的类可以从其他类之一调用方法,但不能从其他第二个类调用方法?

转载 作者:行者123 更新时间:2023-11-30 11:53:47 28 4
gpt4 key购买 nike

我已经在这里潜伏了一段时间,但是我遇到了一个问题,我在为作业编写的一些 Java 程序中无法解决这个问题。我敢打赌它们并不难弄清楚,但我就是不明白。

我一直在犯这样的错误:

RugbyTeamLadderEditor.java:125: cannot find symbol
symbol : method findAveragePoints(java.util.ArrayList<RugbyTeam>)
location: class RugbyTeamLadderEditor
double averagePointsToBePrinted = findAveragePoints(rugbyTeams);

我有三个类,从具有主要方法的类 (RugbyTeamLadderEditor) 中,我可以调用构造函数类,但不能调用其中包含一些方法的其他类(第 1 部分)。我应该用包裹做些什么吗? - 我所知道的是,在我正在学习的这个介绍性编程类(class)中,我没有学到任何关于包的知识,而且我不确定如果我使用它们,它们会如何被接收。

我的代码有几百行,所以我把它们放在了 pastebin 中——我希望这样做没有犯任何失礼:/每个类都在它自己的 .java 文件中。

http://pastebin.com/FrjYhR2f

干杯!

编辑:我的代码的一些片段:

在 RugbyTeamLadderEditor.java 中:

// if the identification number is equal to 5, then print out the average points of all of the teams in the ArrayList
else if (identificationNumber == 5)
{
double averagePointsToBePrinted = findAveragePoints(rugbyTeams);
}

在 Part1.java 中:

/**
* This method takes a RugbyTeam ArrayList and returns a
* double that represents the average of the points of all
* of the rugby teams
*/
public static double findAveragePoints(ArrayList<RugbyTeam> rugbyTeams)
{
// If there are no objects in the ArrayList rugbyTeams, return 0
if (rugbyTeams.size() == 0)
return 0;

// Declare a variable that represents the addition of the points of each team;
// initialise it to 0
double totalPoints = 0;

// This is a code-cliche for traversing an ArrayList
for (int i = 0; i < rugbyTeams.size(); i++)
{
// Find then number of points a team has and add that number to totalPoints
RugbyTeam r = rugbyTeams.get(i);
totalPoints = totalPoints + r.getPoints();
}

// Declare a variable that represents the average of the points of each teams,
// i.e. the addition of the points of each team divided by the number of teams
// (i.e. the number of elements in the ArrayList); initialise it to 0
double averagePoints = totalPoints / rugbyTeams.size();
return averagePoints;

}

它还没有完全完成 - 我仍然需要放入打印语句来打印那个 double,但现在它是无关紧要的,因为我实际上无法让那个 double 接受一个值。

最佳答案

您正在尝试调用方法 findAveragePoints。根据您所说的当前实现,该方法将在类 RugbyTeamLadderEditor 中找到。但是该方法是在类 Part1 中定义的。因此,为了使这项工作正常进行,您可以在方法调用前加上 Part1.(因为它是静态方法),程序应该可以正常工作。


编辑

代码基本上是这样的

double averagePointsToBePrinted = Part1.findAveragePoints(rugbyTeams);

此外,每次您尝试调用另一个类中定义的方法而不是当前类时,您要么必须提供此类的实例,要么在类名前添加(如此处第 1 部分)到调用的方法。

作为侧节点,您应该更改变量 quitProgram 的名称。变量的名称和它的含义相互矛盾。因此,为了让阅读代码的任何人都更清楚,您应该更改名称或处理方式。

关于java - "Cannot find symbol"- 具有 main 方法的类可以从其他类之一调用方法,但不能从其他第二个类调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6081851/

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