我创建了一种方法来检查所有团队中的所有团队,并看到胜率最高的人。一旦循环找到了最高的获胜率,它应该以该胜率回归球队。当我在main方法中调用一行简单的代码时,
System.out.println("The team with the highest winning percentage is: " +highest(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
答案 0 :(得分:2)
是。首先,该方法不是静态的。所以,这个
public String highest(Team[] tm){
应该是
public static String highest(Team[] tm){
然后你需要使用类名(或import static
方法) -
System.out.println("The team with the highest winning percent is: " +
Team.highest(tm));