我想为一个简单的游戏创建一个程序。游戏有3个类:
Player
:包含播放器详细信息,如用户名,姓氏和
姓氏Nimsys
:包含游戏所有方法的系统
功能,最多可以有100名玩家NimGame
:1场比赛仅由2名球员进行问题:我创建了3个类,但我不知道如何将这些类链接在一起。如何使用Scanner
和StringTokenizer
添加播放器名称以分隔用户名,姓氏和姓氏?我的主要方法应该在NimGame
班吗?在我的代码中,当我调用NimPlayer.addPlayer()
时,它会显示错误消息,即类型addPlayer
的方法NimPlayer
未定义。请帮助如何使用方法addPlayer
??
到目前为止,我的代码看起来像这样:
public class NimGame
{
int currentStoneCount, stoneRemovalUpperBound;
private NimPlayer player1, player2;
public static void main (String [] args)
{
System.out.println ("Welcome to Nim");
System.out.println("\n>");
**NimPlayer.addPlayer();**
}
public class NimPlayer
{
String userName, givenName, familyName, newFamilyName, newGivenName;
int gamesPlayed, gamesWon, gamesLost;
/*Constructor*/
public NimPlayer (String userName, String givenName, String familyName,
String newFamilyName, String newGivenName)
{
this.userName = userName;
this.givenName = givenName;
this.familyName = familyName;
this.newFamilyName = newFamilyName;
this.newGivenName = newGivenName;
}
}
import java.util.Scanner;
java.util.StringTokenizer;
public class Nimsys
{
public static void addPlayer()
{
Scanner keyboard = new Scanner (System.in);
String [ ] player = new String [100]; //an array of 100 players
for (int i = 0; i < 100; i++)
{
boolean isInArray = false;
String NimPlayer = keyboard.next();
String delimiters = " add player, "; //add player, comma and blank space
StringTokenizer nameFactory = new StringTokenizer (NimPlayer, delimiters);
String userName = nameFactory.nextToken();
String familyName = nameFactory.nextToken();
String givenName = nameFactory.nextToken();
if (i>0)
{
for (int j = 0; j < 100; j++)
{
if (player [j].equalsIgnoreCase(userName))
{
isInArray = true;
System.out.println("The player already exists.");
System.out.println("\n>");
}
else
{
player [j] = NimPlayer;
System.out.println("\n>");
}
}
}
}
}
}
答案 0 :(得分:0)
我想你想要
NimSys.addPlayer();
严重受损:
player [j] = NimPlayer;
你可能意味着
player [j] = new NimPlayer( ...,...,... );
NimPlayer构造函数所需的所有(太多?)参数。但话说回来,player
是一个String
数组,因此您应该更改此定义。
为什么你认为你需要100名球员?
答案 1 :(得分:0)
支持laune所说的,你不能打电话
NimPlayer.addPlayer();
因为你的addPlayer方法在NimSys类中,而不是NimPlayer。而你的
String [ ] player = new String [100]; //an array of 100 players
需要是NimPlayer类型,因为它包含NimPlayers,而不是字符串。为了能够稍后添加/编辑,我将其更改为List:
List<NimPlayer> player = new ArrayList<NimPlayer>(); //an array of x amount of players
从我可以收集的有关您的代码的内容来看,最好的方法似乎是在NimPlayer类中创建一个没有参数的构造函数
public NimPlayer(){
}
创建一个新的NimPlayer
currentPlayer = new NimPlayer();
并指定如下值:
currentPlayer.userName = nameFactory.nextToken();
currentPlayer.familyName = nameFactory.nextToken();
currentPlayer.givenName = nameFactory.nextToken();
从那里你可以通过比较用户名来比较这个currentPlayer和你阵列中的所有其他NimPlayers:
for (int j = 0; j < player.size(); j++)
{
NimPlayer storedPlayer = player.get(j);
if (storedPlayer.userName.equalsIgnoreCase(currentPlayer.userName))
{
isInArray = true;
System.out.println("The player already exists.");
System.out.println("\n>");
}
else
{
player.add(currentPlayer);
System.out.println("\n>");
}
}