Java 如何初始化对象数组并传递字符串数组?
我正在为一个学校项目创建一个基于文本的骰子游戏。以下代码的作用如下:Java 如何初始化对象数组并传递字符串数组?,java,oop,object,Java,Oop,Object,我正在为一个学校项目创建一个基于文本的骰子游戏。以下代码的作用如下: 提示用户输入玩游戏的玩家数量 创建一个字符串数组,提示用户输入播放器名称,并相应地填充数组 创建一个qwixx对象,并将播放器名称的字符串数组传递给它 在qwixx构造函数中创建播放器对象数组 循环遍历对象数组,并将玩家名称从字符串数组传递给每个对象 使用getName()方法打印出所有玩家的名字 我目前遇到的错误是play()方法指出“players”和“players”都不能解析为变量。欢迎对此提供任何帮助,这是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();
}
}
首先,您已经在main方法中实例化了大量数据,从而导致操作代码是静态的! 第二,下面的行不是声明为全局的“但需要使用static”,因此只能在static main方法内部看到
String players[] = new String[numPlayers];
在主方法中使用的“公共类qwixx”应为“公共静态类qwixx”
以下是一个非静态的“新实例”
qwixx game = new qwixx(players);
但是调用它的问题如下所示,因为静态类不是声明为新的,它只是用一个需要使用
qwixx.play()
更重要的是,任何类名最好是按照其惯例编写的,即以大写字母开头,以帮助阅读代码,并使编译器不会绊倒。e、 g.“公共静态类Qwixx”
“删除静态上下文”或仅在其中一个上下文中完全工作。您的代码有几个问题。但最重要的一点是,在除main之外的每个类中,都没有声明属于该类的任何变量。不要在构造函数中引入类变量。在构造函数外部声明它们,以便它们可以是全局变量。尝试:
public class qwixx {
player[] Players; //declared before using it in any methods / constructor
public qwixx(String[] players) {
Players = new player[players.length]; //value initialized inside the constructor
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());
}
}
}
在main中,您忘记将numlayers声明为int。也这样做
int numPlayers = input_scanner.nextInt
嗯,在你的qwixx类中没有
players
对象。player[]players
:顺便说一句,你的约定被颠倒了。@austinwernli“players”(小写p)是保存玩家名称的字符串数组。我在一些方法中看到了这一点。但是,您需要研究变量范围,因为play()无法访问players
变量anywhere@S.Miller否,类名应使用PascalCase,变量名应为camelCase。
public class qwixx {
player[] Players; //declared before using it in any methods / constructor
public qwixx(String[] players) {
Players = new player[players.length]; //value initialized inside the constructor
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 {
String name;
public player(String playerName) {
name = playerName;
}
public String getName() {
return name;
}
}
int numPlayers = input_scanner.nextInt