我想創建一個簡單的遊戲程序。遊戲有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>");
}
}
}
}
}
}