Java:如何使用Class2变量更改Class1变量

时间:2016-12-21 20:55:56

标签: java class

因此,我的项目是制作一款小型扑克游戏,向玩家询问他们的名字,玩家数量和投注情况。

然而,在此之前,我们需要询问玩家是否想玩新游戏或SAVED游戏。保存的游戏可以硬编码。

我创建了一个class1游戏,对于保存的游戏文件,我创建了class2。我希望class2替换class1的值,但我不知道如何做到这一点。

问题是当我们调用CLASS2时,CLASS1的值不会被CLASS2的值替换。如何从CLASS1获取变量以更新到CLASS2?

我的头等舱:

public class NoC2_Musick extends savedGame
{
    public static void main(String[] args)
    {
        savedGame obj = new savedGame();

        Scanner input = new Scanner(System.in);
        Scanner inputString = new Scanner(System.in);
        System.out.println("Is this a NEW Game or a PREVIOUS game?");
        System.out.println("How many players will join this game?");
        int totalPlayers = input.nextInt();
        String[] players = new String[totalPlayers];

        obj.oldsavedgame();
        System.out.println("What is your name and club?");

        for (int i = 0; i < totalPlayers; i++) {
            players[i] = inputString.nextLine();
        }

        System.out.println("These are the Players: ");
        for (int i = 0; i < totalPlayers; i++) {
            System.out.println(players[i]);
        }

        System.out.println("Place your Bet.");
        int bet = input.nextInt();
    }
}

我的第二课:

public class savedGame
{
    public int oldsavedgame()
    {
        int totalPlayers = 3;
        String[] players;
        players = new String[3];
        players[0] = "Sofia";
        players[1] = "Shawn";
        players[2] = "Tomi";
        int bet = 100;
        System.out.println("Test");
        return totalPlayers;
    }

    public static void main(String[] args)
    {
    }
}

1 个答案:

答案 0 :(得分:0)

我认为你在这里缺少一些关键的东西。我认为您不应该创建一个用于存储旧信息的新类。

只需编写一个将数据加载到实例变量中的方法。

另外,你没有看到这个问题的答案:这是一款新游戏吗?

我会沿着这些方向做些事情(注意:它不完整,但它应该让你朝着正确的方向前进,就像上一场比赛一样):

public class NoC2_Musick {
   int totalPlayers = 0;
   ArrayList<String> players = new ArrayList<String>();
   int bet = 0;

private void LoadSavedGame() {
    totalPlayers = 3;
    players.add("Sofia");
    players.add("Shawn");
    players.add("Tomi");
    bet = 100;
}

public NoC2_Musick() {
    Scanner input = new Scanner(System.in);
    Scanner inputString = new Scanner(System.in);
    System.out.println("Is this a NEW Game? (y/n)");
    char newGame = input.next().charAt(0);

    if(newGame == 'y')
    {
        System.out.println("How many players will join this game?");
        totalPlayers = input.nextInt();

        for (int i = 0; i < totalPlayers; i++) {
            System.out.println("What is your name and club?");
            players.add(inputString.nextLine());
        }
    }
    else {
        LoadSavedGame();
    }

    System.out.println("These are the Players: ");
    for (int i = 0; i < totalPlayers; i++) {
        System.out.println(players.get(i));
    }

    System.out.println("The current bet is: " + bet);

    System.out.println("Place your Bet.");
    int bet = input.nextInt();
}

public static void main(String[] args) {
    new NoC2_Musick();
}

}