【发布时间】:2016-03-16 15:06:18
【问题描述】:
所以我正在准备明天的考试,其中一部分是完成一个静态方法。我已经完成了所有,但有一部分让我感到困惑。我想我可能会寻求帮助。
说明如下,我将令人困惑的部分加粗,并在下面解释原因。
A.在不使用任何标准 Java 数学库方法的情况下完成此静态方法的实现。 仅在抛出异常时使用“if”语句。
/**
* Computes the series n + n^3 + n^5 + ... n^k.
* k-1 is used if k is even.
* @param n the base of the series
* @param k the bound on the exponent of the last term of the series
* @throw IllegalArgumentException when k is less than 1
*/
public double oddSeries(double n, int k) {
if (k < 1) {
throw new IllegalArgumentException("K is less than 1");
}
double tempN = n;
for (int i = 0; i < k; i++)
tempN = tempN + (n * n);
return tempN;
}
所以我抛出了 IllegalArgumentException,并使用了允许的 if 语句。如何检查 k 是否甚至没有 if 语句或 switch 语句? 因为通常我们会这样做
Boolean kEven = false;
if (k % 2 = 0)
kEven = true;
【问题讨论】:
-
k = ( k % 2 == 0 ) ? k -1 : k ;k 将被分配 k-1 如果 k 是偶数,否则它将保持为 k -
我认为三元运算符会被视为使用。
-
你没有正确计算这个
标签: java if-statement methods static