如何获得两场比赛每位球员的平均得分?
编写一个程序,将名称存储为String,并将数字作为团队中11名玩家的int。你的程序应该显示/输出两个游戏中每个玩家的平均得分。
Nick(34),Joey(33),Ken(24),Ryan(11),Josh(3),Simon(6),Dillon(10),Mike(28)和Cameron(5)。< / p>
比赛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();
}
}
}
答案 0 :(得分:0)
当您处理单个数组中的数据属性时,事情往往变得非常繁琐。从概念上讲,在这种情况下,将播放器视为一个唯一的对象来保存其名称,数字和分数更有意义。
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类视为单个游戏并拥有描述每个游戏本身的Object;由10名球员组成。 Object缺少名称和数字属性的getter / setter。
然后,您可以创建一个数组来保存游戏的所有数据。如果您计划拥有多个游戏,您可能希望获得一系列分数而不是每个玩家一个分数。
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());
}
}