gpt4 book ai didi

java - 创建方法和对象

转载 作者:行者123 更新时间:2023-12-02 11:52:32 24 4
gpt4 key购买 nike

大家好,我得到了这个驱动程序类,并被告知要创建类以使驱动程序类正常工作。在大多数情况下,我认为我走在正确的轨道上,但我又不完全确定,因为我是 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
}
}

我的联赛类(class)

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;

}
}

我的团队类(class)

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
}
}

最佳答案

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

该函数返回 String 。您正在传递参数 y ,这是 League 。然后,您尝试返回完全相同的 League就好像它是 String ,这会产生错误。

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

关于java - 创建方法和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47784436/

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