【发布时间】:2014-11-10 14:47:10
【问题描述】:
我创建了一种方法来检查球队数组中的所有球队,看看谁的胜率最高。一旦循环找到最高的获胜百分比,它应该返回具有该获胜百分比的团队。当我在main方法中调用一行简单的代码时,
System.out.println("The team with the highest winning percentage is: " +highest(tm));
我得到一个编译错误,说它找不到最高的方法。它是静态的,因此它可以与团队 tm 数组的主要方法进行通信。如果我不明白某些事情,请向我解释我的误解。
public class teams{
public static void main(String [] argv){
/*Team team1 = new Team("knicks");
Team team2 = new Team("nets");
team1.play(team2);
team1.play(team2);
team2.play(team1);
team2.printrecord();
team1.printrecord();
team2.winpercent();*/
String[] teamnames = {"knicks", "nets", "lakers", "celtics", "heat", "spurs"};
Team[] tm = new Team[teamnames.length]; // creates an array of teams
for (int i=0;i<teamnames.length;i++){ // assigns a team to each string in teamnames
tm[i] = new Team(teamnames[i]);
}//for
for (int i=0;i<teamnames.length;i++){ //nested for loop to have each team play another team once
for(int k=i+1; k<teamnames.length;k++){
if(k!=i)
tm[i].play(tm[k]);
}//nestedfor
}//for
System.out.println("The team with the highest winning percent is: " +highest(tm));
}//main
}//teams
class Team{
double wins;
double losses;
double winningpercent;
String name;
public Team(String n){
name = n;
wins = 0;
losses = 0;
winningpercent = 0;
}//constructor
public void lose(){
losses++;
}//losses
public void win(){
wins++;
}//wins
public void printrecord(){
System.out.println("The W-L record for the " +name+ " is: " +String.format("%d",(long)wins)+"-"+String.format("%d",(long)losses));
}
public void play(Team j){
if((Math.random())<0.5){
System.out.println("The "+j.name+" Have Won!");
j.win();
this.lose();
}//if
else {
System.out.println("The "+name+" Have Won!");
this.win();
j.lose();
}//else
}//play
public double winpercent(){
double winningpercentage = (wins/(losses+wins))* 100;
System.out.println("The Winning percentage for the " +name+" is: " +winningpercentage+"%");
this.winningpercent = winningpercentage;
return winningpercentage;
}//winningpercent
public static String highest(Team[] tm){
String highest = "";
for (int i=0;i<tm.length;i++){
for(int k=i+1;k<tm.length;k++){
if (k!=i && tm[i].winningpercent > tm[k].winningpercent)
highest = tm[i].name;
}//nestedforloop
}//forloop
return highest;
}//highest
}//Team
【问题讨论】:
-
team类中的方法highest不是static。您需要一个team类的实例。new team().highest(tm) -
我将方法设为静态,但它仍然给了我同样的错误。但我明白为什么我必须让它成为一个新实例
-
@BenjiWeiss-因为你的静态方法不能有
Team类型的参数,所以这些方法是随着类的加载而加载的!到时候没有对象或实例被加载! -
如果您使用
static方法,您可以通过class nameTeam.highest(tm)访问它。请参阅下面的答案。