1

this is for a intro programming class i am taking. I have created a Instance method to add a newValue to the totals. It has two parameters in the method: (a letter identifying the amount type, and amount) I was successful on the first parameter. the second is making me struggle. I am suppose to us an if statement. I made it so there is amount type, then i have three letters that are to be used that can be true. I set the if(amountType == false) and the compiler says its a "unreachable statement". The criteria for the if statement is "If the letter for the amount the is invalid (i.e. not T, D, or E), throw an IllegalArgumentException, and message back to user.

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
    {
    }
}    

Any help would be appreciated.

4

4 回答 4

2

您的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;
}
于 2016-02-20T18:02:21.923 回答
1

你必须把return amount里面的第一个if块。

原因是如果第一个if条件是true异常就会抛出。如果它被评估为false,return amount将被执行。

在这两种情况下,第二个if块永远不会被执行

于 2016-02-20T18:02:01.197 回答
0

Unreachable 表示此方法永远无法到达该线路。因为你在没有 if 语句的情况下添加了 return 语句,所以你的第二个 if 语句永远不能被程序执行。所以在你的第一个 if 语句中移动 return 语句,它会起作用。

于 2016-02-20T18:06:55.713 回答
0

您有一个返回金额语句,它始终执行并且它之后的代码即 if 语句不可访问,因为控件总是从返回金额返回。一种可能的解决方案是首先您必须检查金额类型,然后在 else 部分检查金额 < 0 语句并最终返回它。

于 2016-02-20T18:07:18.783 回答