【发布时间】:2018-04-16 23:04:09
【问题描述】:
我正在为一个学校项目创建一个基于文本的骰子游戏。下面的代码旨在如下工作:
- 提示用户玩游戏的玩家数量。
- 创建一个字符串数组并提示用户输入玩家姓名并相应地填充该数组。
- 创建一个 qwixx 对象并将玩家姓名的字符串数组传递给它。
- 在 qwixx 构造函数中创建一个播放器对象数组。
- 循环遍历对象数组并将字符串数组中的玩家名称传递给每个对象。
- 使用 getName() 方法打印出所有玩家的姓名。
我目前遇到的错误是在 play() 方法中指出“玩家”和“玩家”都无法解析为变量。对于 OOP 语言的新手,我们不胜感激。
import java.util.Scanner;
public class driver {
public static void main(String[] args) {
Scanner input_scanner = new Scanner(System.in);
System.out.print("Please enter the number of players (2-5): ");
numPlayers = input_scanner.nextInt();
String players[] = new String[numPlayers];
for (int x = 0; x < numPlayers; x++) {
System.out.print("Please enter the name of Player" + (x+1) + ": ");
players[x] = input_scanner.next();
}
qwixx game = new qwixx(players);
game.play();
input_scanner.close();
}
}
public class qwixx {
public qwixx(String[] players) {
player[] Players = new player[players.length];
for (int x = 0; x < players.length; x++) {
Players[x] = new player(players[x]);
}
}
public void play() {
for (int i = 0; i < players.length; i++) {
System.out.println(Players[i].getName());
}
}
}
public class player {
public player(String playerName) {
name = playerName;
}
public String getName() {
return name;
}
}
【问题讨论】:
-
好吧,你的 qwixx 类中没有
players对象.. -
player[] Players: 顺便说一句,你的约定被颠覆了。 -
@austinwernli “玩家”(小写 p)是保存玩家姓名的字符串数组。
-
我在某些方法中看到了这一点。但是,您需要研究变量范围,因为 play() 无法在任何地方访问
players变量 -
@S.Miller 不,类名应该使用 PascalCase,变量名应该使用 camelCase。