我有以下程序:
class Rational(n: Int, d: Int) {
require(d != 0)
private val g = gcd(n.abs, d.abs)
val numer = n / g
val denom = d / g
def this(n: Int) = this(n, 1)
def this(s: String) = {
val regex: Regex = "^([+-]?(\\d+|\\d*\\.?\\d+)|\\d*\\/?\\d+)$".r
if (!regex.matches(s)) throw new NumberFormatException()
val input: Array[String] = s.split("\\.|\\/")
val num: Int = input(0).toInt
if (input.length equals 1)
this(num, 1) // problem here
else
this(num, input(1).toInt) // problem here
}
}
我尝试用一些逻辑创建构造函数。但是,由于
'Rational'不接受参数
有什么问题吗?
1条答案
按热度按时间z2acfund1#
尝试引入帮助器方法
或者更好的工厂方法(因为构造函数有很多限制)
Executing code in overloaded constructor prior to calling this()
顺便说一下,您也可以使用默认值