这是我正在上编程入门课的。我创建了一个实例方法来向总计添加newValue
。它在方法中有两个参数:(标识金额类型和金额的字母)我在第一个参数上成功了。二是让我挣扎。我想对我们来说是一个if语句。我这样做是为了有金额类型,然后我有三个字母可以使用,可以是真的。我设置了if(amountType == false)
,编译器说这是一个"无法访问的语句"。if 语句的标准是"如果金额的字母无效(即不是 T、D 或 E),则抛出 IllegalArgumentException,并将消息发回给用户。
public double newValue(boolean amountType, double amount)
{
boolean T = amountType;
boolean D = amountType;
boolean E = amountType;
if (amount < 0)
{
throw new IllegalArgumentException("The amount needs to be 0 or larger");
}
return amount;
if(amountType == false)
// if not D, E, T.....then exception
{
throw new IllegalArgumentException("That is an invalid letter value. "
+ "The data will be ignored");
}
else
{
}
}
任何帮助将不胜感激。
您的return
语句妨碍了:一旦执行,之后的任何代码都不会被执行。它必须是要在方法中执行的最后一个指令(不是字面意思)。您可以改为执行以下操作:
public double newValue(boolean amountType, double amount) {
boolean T = amountType;
boolean D = amountType;
boolean E = amountType;
if (amount < 0) // Eliminate constraint 1
throw new IllegalArgumentException("The amount needs to be 0 or larger");
if (!amountType) // Eliminate constraint 2
throw new IllegalArgumentException("That is an invalid letter value. "
+ "The data will be ignored");
// Do your processing, now that you passed all tests
return amount;
}
你必须把return amount
放在第一个if
块内。
原因是,如果第一个if
条件true
则会引发异常。如果它被评估为 false
,return amount
将被执行。
在这两种情况下,第二个if
块将永远不会被执行
"不可到达"表示在此方法中永远无法到达该行。因为您添加了不带 if 语句的 return 语句,所以程序永远无法执行第二个 if 语句。因此,将返回语句移动到第一个 if 语句中,它将起作用。
你有一个返回金额语句,它总是执行,它后面的代码,即 if 语句不可访问,因为控件总是从返回金额返回。一种可能的解决方案是首先您必须检查金额类型,然后在 else 部分中检查金额<0 语句并最终返回它。