创建方法和对象

时间:2017-12-13 02:04:31

标签: java class methods

大家好,所以我获得了这个Driver类,并被告知要创建类以使驱动程序类正常工作。在大多数情况下,我认为即时通讯在正确的轨道,但后来我不完全确定,因为我是java的新手。我收到2个编译错误,因为我没有添加add(temp)方法。说实话,我不确定将该方法放入哪个类。现在我在Team类中有它但是我得到了一个编译错误。如果有人能给我一些见解,将会非常感激。

public class Driver{
 public static void main(String args[]) throws Exception{
    //All information is stored in input.txt and is being
    //read in below.
    Scanner input = new Scanner(new File("input.txt"));
    //Creates a new League and passes in a String signifying
    //which league it is.
    League american = new League("AL");
    League national = new League("NL");
    for(int i=0; i<15; i++){
        //Creates a new team and adds the current team
        //to the american league.
        //You can assume there are exactly 15 teams in each league.
        Team temp = new Team(input.next());
        american.add(temp);   // compile error
    }
    for(int i=0; i<15; i++){
        //Creates a new team and adds the current team
        //to the national league.
        //You can assume there are exactly 15 teams in each league.
        Team temp = new Team(input.next());
        national.add(temp);   // compile error 
    }
    }

我的联赛班级

public class League{
private String league;

public League(String League){
     league = League;
}

public void setLeagueAmerican(String League){
    this.league = League;
}

public String getLeagueAmerican(){
    return league;
}

public void setLeagueNational(String national){
    this.league = national;
}

public String getLeagueNational(){
    return league;
}


public void League( String League){

     league = League;

}
}

我的团队课程

public class Team
{
// instance variables - replace the example below with your own
private String team;

/**
 * Constructor for objects of class Team
 */
public Team(String Team)
{
    team = Team;
}

public void setTeam(String Team){
    this.team = Team;
}

public String getTeam(){
    return team;
}



public String add(League y)
{

    return y;       //compiling error 
}
}

1 个答案:

答案 0 :(得分:1)

public String add(League y)
{
    return y;       //compiling error 
}

此函数返回String。您正在传递参数y,即League。然后,您尝试返回与League完全相同的String,这会产生错误。

将返回类型更改为League,或者不返回y,而是返回有意义的字符串(甚至是y.toString()