需要帮助编写文字游戏

我在Eclipse中收到一条错误消息:   表达式的类型必须是数组类型,但它已解析为Player。 我创建了一个对象Player。用户通过JOptionPane输入他们想要的玩家数量。我试图将玩家名称存储在一个数组中。
 public class Project3 {
 public static void main(String[] args){

  String input = JOptionPane.showInputDialog("Enter the number of players: ");
  int numPlayers = Integer.parseInt(input);
  Player nameOfPlayers;

  for(int i = 0; i < numPlayers; i++){
   nameOfPlayers[i] = new Player(JOptionPane.showInputDialog("Enter the number of players: "));
   if (input == null || input.equals(" ")) throw new IllegalArgumentException("Must enter valid name!!!");

  }

 }
这是我的班主任:
public class Player {
 private String name;

 public Player(String name){
  if(name == null || name.equals(" "))
   throw new IllegalArgumentException("Must enter a name. ");

  this.name = name;

 }


 public void addWord(Word w){

 }
 public int getScore(){

 }
}
    
已邀请:
你使用的是旧值
input
(从你要求玩家数量时开始)。你可能想要更像这样的东西:
for(int i = 0; i < numPlayers; i++){
   input = JOptionPane.showInputDialog("Enter the player's name: ");
   if (input == null || input.equals(" "))
       throw new IllegalArgumentException("Must enter valid name!!!"); 
   nameOfPlayers[i] = new Player(input);
}
编辑:根据您发布的错误消息,问题是
nameOfPlayers
不是数组,但您将其视为一个数组。请尝试
Player[] players = new Player[numPlayers];
。     
您还没有创建数组。 也许你的意思是
Player [] nameOfPlayers = new Player[somevalue];
    
看起来你在粘贴的第一段代码末尾缺少一个结束括号(})。你没有正确关闭
Project3
课程。 编辑:现在我知道错误,
nameOfPlayers
需要是一个数组,您可以在代码中以数组的形式访问它。您还需要在初始化时将其大小调整为
numPlayers
。     
您将
nameOfPlayers
定义为类型
Player
- 不是
Player
的数组。它应该是
Player[] nameOfPlayers;
在分配
Player
实例之前,您还需要对其进行初始化。     

要回复问题请先登录注册