如何获得两场比赛每个玩家的平均分数?
编写一个程序,将名称存储为字符串,将数字存储为团队中 11 名玩家的 int。您的程序应显示/输出每个玩家在两场比赛中的平均得分。
尼克(34(、乔伊(33(、肯(24(、瑞安(11(、乔什(3(、西蒙(6(、狄龙(10(、迈克(28(和卡梅隆(5(。
第1局: 4, 3, 3, 2, 4, 5, 6, 6, 7, 7, 8.第2局:8,4,3,3,5,5,7,8,8,9,5。
import java.util.Scanner;
import java.util.Arrays;
public class BasketballStats {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] jerseyNumber = {34, 33, 24, 11, 3, 13, 6, 4, 28, 10};
String[] playerName = {"Jim", "Joe", "Ken", "James", "John", "Bud",
"Clark", "Barry", "Jose", "Paul"};
int[] game1 = new int[11];
int[] game2 = new int[11];
for (int i = 0; i < 10; i++)
System.out.printf("Number %d: %s n" , jerseyNumber[i],
playerName[i]);
}
public void setGame1Score() {
int[] jerseyNumber = {34, 33, 24, 11, 3, 13, 6, 4, 28, 10};
String[] playerName = {"Jim", "Joe", "Ken", "James", "John", "Bud", "Clark",
"Barry", "Jose", "Paul"};
Scanner input = new Scanner (System.in);
for (int i = 0; i < 10; i++) {
System.out.println("For game 1, how many points does he score?");
int game2 = input.nextInt();
}
}
}
当您处理单个数组中的数据属性时,事情往往会变得非常乏味。从概念上讲,在这种情况下,将玩家视为唯一对象以保存其姓名、数字和分数更有意义。
public class Player {
private String name;
private int number;
private int scores[];
private int currentGame = 0;
public Player(String name, int number, int numGames) {
this.name = name;
this.number = number;
this.scores = new int[numGames];
}
// Getters and Setters
public String getName() { return name; } // Required
public void addScore(int score) {
if (currentGame < scores.length) {
scores[currentGame++] = score;
}
}
public int getAverage() {
int total = 0;
for (int i = 0; i < currentGame; i++) {
total += scores[i];
}
return total / currentGame;
}
@Override
public String toString() {
return String.format("%s (%s) : avg %d", name, number, getAverage());
}
}
然后,您可以使用玩家的姓名、号码和他们玩的游戏数量来实例化玩家。但是,您可能希望将 Player 类视为单个游戏,并拥有一个描述每个游戏本身的对象;由10名玩家组成。对象缺少名称和数字属性的获取者/设置器。
然后,您可以创建一个数组来保存游戏的所有数据。如果您计划进行多个游戏,则可能需要一个分数数组,而不是每个玩家一个分数。
public static final String[] playerName = {"Jim", "Joe", "Ken", "James", "John", "Bud",
"Clark", "Barry", "Jose", "Paul"};
public static final int[] jerseyNumber = {34, 33, 24, 11, 3, 13, 6, 4, 28, 10};
public Player[] createGame(int numGames) {
Player[] players = new Player[10];
for (int i = 0; i < 10; i++) {
players[i] = new Player(playerName[i], jerseyNumber[i], numGames);
}
return players;
}
然后当你需要以某种方式获得分数时。
public void getScore(Player[] players, int numGames) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < numGames; i++) {
System.out.println("Game " + i);
for (Player player : players) {
System.out.print(player.getName() + " : ");
player.addScore(input.nextInt());
}
}
}
public void getAverage(Player[] players) {
for (Player player : players) {
System.out.println(player.toString());
}
}