【发布时间】:2019-11-11 21:43:02
【问题描述】:
我是 Java 新手,我正在尝试编写一个带有构造函数和方法的类,这些构造函数和方法可以将两个数字相加和相除,并比较一个对象是否大于或等于另一个对象。但我收到一个错误:The method plus(int) in the type Compare is not applicable for the arguments (Compare)。怎么了?
代码如下:
public class Compare {
// fields
private int number;
private int plus;
private double div;
// constructor
public Compare (int n) {
number = n;
}
public int plus (int x) {
return this.number + x;
}
public int div (int x) {
return this.number / x;
}
public boolean isLargerThan (int x) {
return this.number > x;
}
public boolean isEqualTo (int x) {
return this.number == x;
}
public static void main(String[] args) {
Compare n1 = new Compare(9);
Compare n2 = new Compare(4);
Compare sum = n1.plus(n2);
Compare div = n1.div(n2);
boolean check1 = sum.isLargerThan(n1);
boolean check2 = div.isLargerThan(n2);
boolean check3 = div.isEqualto(sum);
}
}
要求是使用 Compare 构造函数创建 sum 和 div 对象,该构造函数将等于 n1 加上 n2,加上适用的 plus 方法或除法。
【问题讨论】:
-
boolean check1 = sum.isLargerThan(n1);,n1的类型是什么,你通过定义public boolean isLargerThan (int x) {期待什么? -
n1 必须由比较器初始化。以便可以将方法应用于它。方法 public boolean isLargerThan 将应用于 n1,与 n2 或由 Compare 初始化的任何对象进行比较。
-
SMA 的意思是您声明了采用
integers的方法,但您将其传递给Compare。当你这样做时,你希望编译器做什么?
标签: java oop methods constructor