如何为数组中创建的对象分配和获取值?

时间:2019-08-12 01:48:14

标签: java arrays object

目前,Java是一种业余爱好,并且正在制作一些小型游戏项目来强化这些概念。因此,为此,我制作了一种方法,该方法创建对象数组,在本例中为“计算机”对象。之所以这样做,是因为我希望用户在启动时决定要与多少计算机对手对抗,而不是硬编码一组对手。现在,我想为每个Computer对象分配和检索一个值。例如计算机名称,下注金额和掷骰子。

public class Computer {
    static int bet;
    static int guess;
    int cash;
    static Computer[] c;

    public static void create(int numComps) {

        c = new Computer[numComps];

        for (int i = 0; i < numComps; i++) {
            c[i] = new Computer();
            c[i].cash = Game.startCash;
            c[i].bet = bet();
            c[i].guess = guess();
            c[i].display();
        }
    }

    public static int bet() {
        bet = Rng.rand(Game.startCash / 50) * 50;
        return bet;

    }

    public static int guess() {
        guess = Dice.roll();
        return guess;

    }

    public void display() {
        String name = "Computer ";
        System.out.println("My name is " + name + " i bet " + bet + " and guess " + guess);
    }
}

当我执行Computer.create(5)时我得到

My name is Computer  i bet 150 and guess 9
My name is Computer  i bet 50 and guess 3
My name is Computer  i bet 450 and guess 11
My name is Computer  i bet 250 and guess 11
My name is Computer  i bet 50 and guess 10

此输出显示工作状态,但我认为我的工作不正确。对于名称,我希望语法类似于:name =“ Computer” + c [i]。结果是“计算机1”,“计算机2”,“计算机3”等,不确定如何正确执行此操作。并有一个单独的下注和猜测要分配给每个单独的对象。现在,我认为它只是显示一个随机数,而不是将该值分配给特定对象。

1 个答案:

答案 0 :(得分:1)

betguess成员变量不应该是静态的。

要显示ID,您可以添加一个新的int成员变量,在循环中对每台计算机进行初始化时将其设置为i,并更新display()方法进行打印它。

public class Computer {
    int id;
    int bet;
    int guess;
    int cash;
    static Computer[] c;

    public static void create(int numComps) {
        c = new Computer[numComps];

        for (int i = 0; i < numComps; i++) {
            c[i] = new Computer();
            c[i].id = i;
            c[i].cash = Game.startCash;
            c[i].bet = bet();
            c[i].guess = guess();
            c[i].display();
        }
    }

    public static int bet() {
        return Rng.rand(Game.startCash / 50) * 50;
    }

    public static int guess() {
        return Dice.roll();
    }

    public void display() {
        String name = "Computer ";
        System.out.println("My name is " + name + id + " bet " + bet + " and guess " + guess);
    }
}