开发者

Need help programming a word game

I am getting an error message in Eclipse:

The type of the expression must be an array type but it resolved to Player.

I have created an object Player. The user through the JOptionPane enters how many players they want. I am trying to store the players names in an array.

 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!!!");

  }

 }

Here's is my Class Player:

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 get开发者_运维知识库Score(){

 }
}


You haven't create an array. Maybe you mean Player [] nameOfPlayers = new Player[somevalue];


You're using the old value of input (from when you were asking for the number of players). You probably want something more like this:

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);
}

Edit: Based on the error message you posted, the problem is that nameOfPlayers isn't an array, but you're treating it like one. Try Player[] players = new Player[numPlayers]; instead.


It looks like you're missing an ending brace (}) at the end of the first bit of code you pasted. You haven't closed off the Project3 class properly.

Edit: now I know the error, nameOfPlayers needs to be an array for you to access it as an array later on in the code. You also need to size it to numPlayers on its initialisation.


You are defining nameOfPlayers as type Player - not an array of Player. It should be

Player[] nameOfPlayers;

You will need to initialize it as well before you assign Player instances.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜