我刚刚练习 Java,对此还很陌生。我只是想创建一个随机数生成器程序来跟踪玩家的获胜、失败、获胜百分比和总获胜金额。该程序的逻辑是,玩家每次 session 有 3 次机会,计算机会生成一个随机数,玩家需要猜测或更确切地说应该匹配该数字。
我目前有三个类:Game(包含主要逻辑)、Player(应该有获胜/失败等......这是我的猜测)和 RandomNumberGenerator(生成随机数)。
我已经开始使用该程序,但很困惑是否需要将 gamesWon、gamesLost、totalWinnings、winPercent 声明为玩家类中的单独变量?任何帮助将不胜感激。
这是迄今为止的玩家类别:
public class Player {
private String name;
private int totalWinnings;
private int gamesWon;
private int gamesLost;
public Player() {
this.name = "default";
this.totalWinnings = 0;
this.gamesWon = 0;
this.gamesLost = 0;
}
public Player(String name) {
this.name = "default";
this.totalWinnings = 0;
this.gamesWon = 0;
this.gamesLost = 0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGamesWon() {
return gamesWon;
}
public void setGamesWon(int gamesWon) {
this.gamesWon += gamesWon;
}
public int getGamesLost() {
return gamesLost;
}
public void setGamesLost(int gamesLost) {
this.gamesLost += gamesLost;
}
public void setTotalWinnings(int totalWinnings) {
this.totalWinnings += totalWinnings;
}
public int getTotalWinnings() {
return totalWinnings;
}
}
游戏类别:
public class Game {
private Player player;
private LuckyNumberGenerator lng;
public Game() {
player = new Player();
lng = new LuckyNumberGenerator();
}
private void eventLoop() {
Scanner scanner = new Scanner(System.in);
int choice = 0;
boolean exit = false;
while (!exit) {
System.out.println("Welcome to the Guessing Game");
System.out.println("==============================");
System.out.println("(1) Set Up New Player");
System.out.println("(2) Play One Round");
System.out.println("(3) Player Win Statistics");
System.out.println("(4) Display Game Help");
System.out.println("(5) Exit Game");
System.out.println("Choose an option: ");
try {
choice = Integer.parseInt(scanner.nextLine());
if (choice < 1 || choice > 5) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
} catch (NumberFormatException e) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
switch (choice) {
case 1:
createNewPlayer(scanner);
break;
case 2:
guessNumber(scanner);
break;
case 3:
printStatistics();
break;
case 4:
printHelp();
break;
case 5:
exit = true;
}
}
scanner.close();
}
}
最佳答案
根据 OO 设计,gamesWon、gamesLost、totalWinnings 和 winPercent 等属性应该仅位于 Player 类中(正确)。
您有一个参数化构造函数,它与默认或零参数化构造函数相同。您没有使用传递名称(字符串)作为参数,因为您将每个对象的名称设置为“默认”相同的字符串,无论传递的值如何。
询问用户从 1 到 100(选择)之间没有任何意义,因为您只有 5 个案例需要切换。
您不应该将扫描仪对象传递给其他方法,因为它应该仅用于扫描数据并在使用后立即关闭它。 您可以使用您需要的任何方法来定义扫描仪对象。
关于java - 计算胜/负、胜率和总胜率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39075191/