java写一段代码①第一个类Player至少包含两个成员变量. 1.name---姓名 2.goals---进球数(int 类型, 代表这个队员在这次世界杯的进球数量) ②第二个类Team至少包含三个成员变量 1.name---球队名字(String 类型,代表球队国家) 2.ranking---球队排名(int类型,只能取值1,2,3,4 , 并且数值的大小代表球队的水平) 3.2 players---2个球员(Player类型的, 球队的进球数会平均分给他们两个,若球队的进球数是单数,则随机分配给一个
时间: 2024-01-22 08:21:21 浏览: 154
下面是代码实现:
```
public class Player {
private String name;
private int goals;
public Player(String name, int goals) {
this.name = name;
this.goals = goals;
}
public String getName() {
return name;
}
public int getGoals() {
return goals;
}
}
public class Team {
private String name;
private int ranking;
private Player player1;
private Player player2;
public Team(String name, int ranking, Player player1, Player player2) {
this.name = name;
this.ranking = ranking;
this.player1 = player1;
this.player2 = player2;
}
public String getName() {
return name;
}
public int getRanking() {
return ranking;
}
public Player getPlayer1() {
return player1;
}
public Player getPlayer2() {
return player2;
}
public int getGoals() {
int totalGoals = player1.getGoals() + player2.getGoals();
if (totalGoals % 2 == 0) {
return totalGoals / 2;
} else {
// 随机分配一个球员多进一个球
int random = new Random().nextInt(2);
if (random == 0) {
return totalGoals / 2 + 1;
} else {
return totalGoals / 2;
}
}
}
}
```
使用示例:
```
Player player1 = new Player("张三", 3);
Player player2 = new Player("李四", 2);
Team team = new Team("中国", 3, player1, player2);
int goals = team.getGoals();
System.out.println(team.getName() + "在本次世界杯的进球数为:" + goals);
```
输出结果:
```
中国在本次世界杯的进球数为:3
```
阅读全文