如何用另一个对象制作一个对象

huangapple go评论105阅读模式
英文:

How to make an object out of another object

问题

基本上我正在尝试使endPosition获取position的值并添加那些x,y值。

我只是在努力找出正确的语法来实现这样做。

Point position = new Point((int) (Math.random() * (max - min)), (int) (Math.random() * (max - min)));
Point endPosition = new Point();
Point endPosition = (position.x + 2);
英文:

Basically I am trying to make an endPosition take the values from position and add to those x, y values.

I am just struggling to figure out the right syntax to do so.

Point position= new Point((int) (Math.random()*(max - min)), (int) (Math.random() *(max - min)));
Point endPosition = new Point();
Point endPosition = (position.x + 2);

答案1

得分: 3

只需在构造函数中创建一个新对象,并传入所需的参数。

Point position = new Point((int) (Math.random() * (max - min)), (int) (Math.random() * (max - min)));
Point endPosition = new Point(position.x + 2, position.y + 3);
英文:

Simply create a new object and pass the required arguments in the constructor.

Point position= new Point((int) (Math.random()*(max - min)),(int) (Math.random() *(max - min)));
Point endPosition = new Point(position.x+2, position.y+3);

答案2

得分: 0

所以你想要添加(int) (Math.random()*(max - min)(int) (Math.random() *(max - min)

你可以在类中创建两个数据成员,称为 int xint y,以及第三个数据成员,称为 int sum

然后进行以下操作:

class Point {
    int x;
    int y;
    int sum;
    
    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

然后在主函数中,简单地创建该类的一个实例。

Point position = new Point((int) (Math.random()*(max - min)), (int) (Math.random() *(max - min)));

position.sum = position.x + position.y;
英文:

So you want to add (int) (Math.random()*(max - min) and (int) (Math.random() *(max - min)

You can create 2 data member in the class say int x and int y and a third data member say int sum

and do the following

class Point{
int x;
int y;
int sum;
Point(int x,int y){
    this.x = x;
    this.y = y;
   }
}

And then in main Simply create an instance of the class.

Point position = new Point((int) (Math.random()*(max - min)),(int) (Math.random() *(max - min)));

position.sum = position.x+position.y;

huangapple
  • 本文由 发表于 2020年9月13日 15:53:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63868447.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定