我收到此错误:
Fraction类中的构造函数分数不能应用于给定类型
我认为问题在于最后一种方法multiply
。我正在尝试返回一个新的对象分数实例,其中分子字段乘以参数。
public class Fraction {
private int numerator;
private int denominator;
public Fraction() {
numerator = 0;
denominator = 1;
}
public void setNumerator(int newNum) {
numerator = newNum;
}
public void setDenominator(int newDenom) {
denominator = newDenom;
}
public int getNumerator() {
return numerator;
}
public int getDenominator() {
return denominator;
}
public double getValue() {
return (double) numerator/denominator;
}
public String toString() {
return numerator + "/" + denominator;
}
public Fraction multiply(int num) {
return new Fraction(numerator, denominator);
}
}
答案 0 :(得分:7)
new Fraction(numerator, denominator)
- 您Fraction
的构造函数不接受参数; public Fraction()
如果您需要此功能,则需要实现它
public Fraction()
{
this(0, 1);
}
public Fraction(int numerator, int denominator)
{
this.numerator = numerator;
this.denominator = denominator;
}
作为例子
答案 1 :(得分:4)
你的Fraction
类中没有匹配的构造函数,它将分子和分母作为输入,因此错误就在这一行:
return new Fraction(numerator, denominator);
定义一个构造函数来获取参数,可能是这样的:
public Fraction(int numerator, int denominator)
{
this.numerator = numerator;
this.denominator = denominator;
}