我在Eclipse中收到一条错误消息:
表达式的类型必须是数组类型,但解析为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];
。关于java - 需要帮助编写文字游戏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4119561/