Reputation: 13
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.
Upvotes: 1
Views: 3356
Reputation: 2037
You have to put the return amount
inside the first if
block.
The reason is that if the first if
condition is true
an exception will be thrown. And if it is evaluated as false
, return amount
will be executed.
In both cases, the second if
block will never be executed
Upvotes: 1
Reputation: 653
You have a return amount statement and it always executes and the code after it i.e if statement is not reachable because the control always return from return amount. One possible solution is first you have to check for amount type and then in the else part check for amount < 0 statement and the end return it.
Upvotes: 0
Reputation: 1072
Unreachable means that the line can never be reached in this method. Because you add return statement without if statement, your second if statement can never be execute by program. So move return statement in your first if statement, and it will work.
Upvotes: 0
Reputation: 17132
Your return
statement is getting in the way: once executed, any code that falls afterwards will not be executed. It needs to be the last instruction (not literally) to be executed in your method. You can do this instead:
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;
}
Upvotes: 2