我正在做一个练习,其中我必须创建方法 add
,但是由于p和v被定义为对象,我在练习中给出了'm having a hard time figuring out how I can define this method in the syntax I'(我只允许更改方法) .
我想添加两个输入5和17,以便它返回22.我've done a lot of research into other questions where I'看到他们把它写成 Positiv(p + v)
但这不是很有效 .
public class Positiv {
public static void main(String[] args) {
try {
Positiv p = new Positiv(5);
Positiv v = new Positiv(17);
p.add(v);
System.out.println(p.get());
} catch (Exception e) {
e.printStackTrace();
}
}
private int n;
public Positiv(int n) {
if (n < 0) { throw new IllegalArgumentException("exception");
}
this.n = n;
}
public static Positiv add(Positiv v)
{
return new Positiv(n + v);
}
public int get() {
return n;
}
}
2 回答
在你的
add
方法中:你返回一个全新的
Positiv
对象 . 但是(如果我错了,请纠正我)看起来好像你只想添加两个n
字段 . 您可以通过将this.get
添加到v.get
来执行此操作:哪个会返回
22
this教程