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

我只是想问一下标题的内容。 这是我的例子,我希望x成为新的随机集合。 我也是这样做的,一个电话开关不支持等号,所以 – 意味着相等。 括号也是(。所以当我做构造函数时 – 新的构造函数(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.我正在开发的游戏涉及随机化,然后值应该将它们赋予新创建的角色的参数。

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

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

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

 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 + ""); 

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

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

 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. value未定义为Opponent中的字段

也许这样的事情。 我把随机数生成给你:

 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); } }