在Java中为构造函数中的参数设置值

时间:2013-11-21 02:12:54

标签: java parameters constructor

我只是想问一下标题的内容。这是我的例子,我希望x成为新的随机集合。我也是这样做的,手机开关不支持等号,所以 - 意味着相等。支架也是(。所以当我这样做时 构造函数a - 新构造函数(x)

public class Opponent (

    public static x - 0;

    public Opponent (int value) (
        value - 5;
    )

    public static void main (String() args) (
        Opponent character1 - new Opponent(x)
        System.out.println(x);
    )
)

基本上我希望x成为5.我正在开发的游戏涉及随机化,然后值应该将它们提供给新创建的角色的参数。

我遇到的问题是它不起作用,这意味着它可能无法做到这一点。

无论如何我能做到这一点。

我道歉,如果这是一个愚蠢的问题,但无论如何,谢谢。

3 个答案:

答案 0 :(得分:1)

public class Opponent {

    public static int x = 0;

    public Opponent (int value) {
        x = value;
    }

    public static void main (String[] args) {
        int y = 5; // random number I chose to be 5
        Opponent character1 = new Opponent(y);
        System.out.println(character1.x + ""); // will display 5 (which was int y)
    }
}

问题列表:

•要打开/关闭方法/类,不要使用 ();您必须使用{}

public static void main (String() args)需要为public static void main (String[] args)

•要初始化某些内容,请使用= -

•您需要为x提供一种类型,例如int

•定义Opponent character1 - new Opponent(x)时,最后需要使用分号。

•您已将x作为Opponent character1 = new Opponent(y);行中的参数传递,即使您尝试使用参数定义x 也是如此。给它一个不同的价值。


一个注意事项:为什么要在类中定义类的实例?而不是使用它:

Opponent character1 = new Opponent(y);
System.out.println(character1.x + "");

你可以这样写:

System.out.println(Opponent.x + "");

但是,如果您从其他班级访问班级character1,则可以创建Opponent

答案 1 :(得分:0)

老实说,我不知道你的问题是什么,但试试这个:

public class Opponent {

    public int x;

    public Opponent (int value) {
        x = value;
    }

    public static void main (String[] args) {
        Opponent character1 = new Opponent(5);
        System.out.println(character1.x); // this will output: 5
    }
}

您的问题存在一些问题:

  1. 您是否正在尝试初始化一个静态变量,认为它是一个实例变量?
  2. x未在main()
  3. 中初始化
  4. 值未定义为“对手”中的字段

答案 2 :(得分:-1)

也许是这样的。我将random number generation留给您:

public class Opponent
{
    private int score;

    public Opponent()
    {
        // you probbaly want to override this with
        // a random number generator
        this.score = 0;
    }

    public Opponent(int value)
    {
        this.score = value;
    }

    public int getScore()
    {
        return this.score;
    }

    public void setScore(int score)
    {
        this.score = score;
    }

    public static void main(String[] args)
    {
        Opponent character1 = new Opponent();
        Opponent character2 = new Opponent(5);

        int result = character1.getScore() - character2.getScore();
        System.out.println(result);
    }
}