Why is it saying my If statement is unreachable? - java

The compiler is saying that the statement is unreachable on the line with the if statement. I'm not overly familiar with Java.
public double calculate()
{
total_usage_charge = getUsageCharge();
total_charge = rate + total_usage_charge;
return total_charge;
if("A".equals(package_plan.toUpperCase()) && getUsageCharge() > 14.95)
{
sB = getUsageCharge() - 14.95;
System.out.println("You're spending more money than you should. If you switched to Plan B you would save:$" + sB);
}
}

Because you're returning from the method by executing this:
return total_charge;
So the next statement is never going to be executed.

You return (return total_charge;) from your method just before the if statement. No code after a return can ever be executed (except the relevant finally block if your return statement is located in a try...catch...finally).

You are returning before calling if statement so its unreacheable .
A method returns to the code that invoked it when it reaches a return statement.

return total_charge;
You method returns at this point, post which any code won't be reachable.

you have putted return statement above IF. so when compiler comes on this statement everytime it returns from there and if can not executed anytime so, remove returns statement or put it below if Condition.

Code will not be executed after return statement.following block of code is causing problem i.e.
return total_charge;
So you will have to remove this line or put it at the end.!

public double calculate()
{
total_usage_charge = getUsageCharge();
total_charge = rate + total_usage_charge;
if("A".equals(package_plan.toUpperCase()) && getUsageCharge() > 14.95)
{
sB = getUsageCharge() - 14.95;
System.out.println("You're spending more money than you should. If you switched to Plan B you would save:$" + sB);
}
return total_charge;
}
Just like that ;)

**if("A".equals(package_plan.toUpperCase()) && getUsageCharge() > 14.95)
{
sB = getUsageCharge() - 14.95;
System.out.println("You're spending more money than you should. If you switched to Plan B you would save:$" + sB);
}
else if("A".equals(package_plan.toUpperCase()) && getUsageCharge() > 19.95)
{
sC = getUsageCharge() - 19.95;
System.out.println("You're spending more money than you should. If you switched to Plan C you would save:$" + sC);
}
else if("B".equals(package_plan.toUpperCase()) && hours < 10)
{
sA = getUsageCharge() - 9.95;
System.out.println("You're spending more money than you should. If you switched to Plan A you would save:$" + sA);
}
else if("B".equals(package_plan.toUpperCase()) && getUsageCharge() > 19.95)
{
sC = getUsageCharge() - 19.95;
System.out.println("You're spending more money than you should. If you switched to Plan C you would save:$" + sC);**
}**
Did u meant to comment it, if yes do it right. or this is error and unreachable statement according to the code provided.
Comment it with /* your code to comment */

Related

Compilation error in BlueJ- if else with return statement

I am using BlueJ IDE to write java programs.
I have a method with String return type. I have put the return statements within if-else, such that if the boolean variable "flag" has true value, then one value is returned, while if the value is false, another value is returned.
Now, the problem is that BlueJ asks for another return statement even after this, as shown below.
If I give another return after if-else, it works.
Why is this happening? I had learnt that there can be no statements after the return statement. So, why is the compiler asking for another return statement?
If someone wants the code for cut-paste purposes, here it is. This code is meant to convert binary numbers to their decimal equivalents, including fractions, but no negative numbers.
public class Conversions{
protected String Binary_Decimal(String str){
int a = str.indexOf('.');
boolean flag = false;
if (a == -1){
str += ".0";
a = str.indexOf('.');
flag = true;
}
String bd = str.substring(0, a);
String ad = str.substring(a + 1);
a = 0;
double num = 0;
for (int i = bd.length() - 1; i >= 0; i--){
num += Math.pow(2, a) * Integer.parseInt(Character.toString(str.charAt(i)));
a++;
}
if (flag == true){
return Integer.toString((int) num);
}
else if (flag == true) {
a = -1;
for (int i = 0; i < ad.length(); i++){
num += Math.pow(2, a) * Integer.parseInt(Character.toString(str.charAt(i)));
a--;
}
return String.valueOf(num);
}
return String.valueOf(num); //<-- WHY DOESN'T IT RUN WITHOUT THIS EXTRA return?
}
}
Here, str is the string that is input by the user using a different method Input().
The issue is that you wrote an if - else as an if - else if. The compiler does not understand or care that the two conditions you have are mutually exclusive and therefore cover all cases. Given how you wrote the branches, you need an explicit else or a catchall return for the compiler to be assured that the function always returns a String.
This is one example of why it is a bad idea to explicitly spell out the else when you have a set of conditions. The more important reason being that your if will often contain something much more complex and you might not negate it properly.
Delete the second ELSE IF clause and put the block directly after the first return statement, and consider that flag is a boolean. As follows:
if (flag) return Integer.toString((int) num);
a=-1;
for(....){
....
}
return String.valueOf(num);
In this way, the compiler should not notify you that error.
So, why is the compiler asking for another return statement?
Because you are missing a default return statement.
What if none of the conditions you have satisfied ? There must be something return default right ? That is what the issue is. That is why it is getting compiled when you uncomment that line.
Or even , you have an else statement, your program will have at least one satisfied return and it gets compiled too. Try it.
I had learnt that there can be no statements after the return statement.
This statement comes with some conditions. You have the return statement inside the if condition. So if your expression is not true, there is no way that the return gets execute.

Why do i need an additional return statement in a method when using if-else and all possible conditions are met

My question is about return statements in a method. In the method calculatePrice below it accepts an integer as a parameter and the if-else block tests for every possible case (below 0, within the ranges, and at the top of the range) and has a return statement for each. The code below compiles with an error because I don't include a return statement at the bottom, but I'm confused why I need that since it will meet one of the conditions before it ever gets to that last return. Thanks!
import java.text.DecimalFormat;
public class ElectricityCostSolution {
public static void main(String[] args) {
DecimalFormat price = new DecimalFormat("$##.00");
int test1 = 984;
int test2 = 2984;
int test3 = 5984;
System.out.println("The price for " + test1 + "kwh of electricity is " + price.format(calculatePrice(test1)));
System.out.println("The price for " + test2 + "kwh of electricity is " + price.format(calculatePrice(test2)));
System.out.println("The price for " + test3 + "kwh of electricity is " + price.format(calculatePrice(test3)));
}
public static double calculatePrice(int hours) {
final double LEVEL_ONE_PRICE = .0577;
final double LEVEL_TWO_PRICE = .0532;
final double LEVEL_THREE_PRICE = .0511;
if (hours <= 1000) {
return hours * LEVEL_ONE_PRICE;
} else if (hours > 1000 && hours <= 5000) {
return (1000 * LEVEL_ONE_PRICE) + (hours - 1000) * LEVEL_TWO_PRICE;
} else if (hours > 5000) {
return (1000 * LEVEL_ONE_PRICE) + (4000 * LEVEL_TWO_PRICE) + (hours - 5000) * LEVEL_THREE_PRICE;
}
}
}
Why do you need that 3rd if? It's always true.
The compiler will not actually evaluate all your conditions to see if both decisions can really happen. In general, it's not possible to make these sorts of determinations automatically.
If you make the last condition an else instead of an "else if", then you don't need another return.
That is because you have added if and else if statements, there is no return statement for the scenario when any of these conditions aren't met.
Perhaps you should add an else block of code or simply add one return statement at the end of the code or you can just change your existing code to following
if(hours <= 1000)
{
return hours * LEVEL_ONE_PRICE;
}
else if(hours>1000 && hours <= 5000)
{
return (1000 * LEVEL_ONE_PRICE) + (hours-1000) * LEVEL_TWO_PRICE;
}
else
{
return (1000 * LEVEL_ONE_PRICE) + (4000 * LEVEL_TWO_PRICE) + (hours - 5000) * LEVEL_THREE_PRICE;
}
Maybe it's because Java doesn't know that all conditions are met. When you compile, it looks for code errors, but I don't think it makes sure your if-else statements are all met. Just in case, it makes you add a return false; or return true; at the end to make sure that there are no problems. I think it is just that the developers don't want to add a check to Java. Another example of this is setting a variable equal to something else. Shouldn't it know the difference between var1 = var2 and if (var1 = var2)?
Correct me if I'm wrong.
-Ben
It is because the compiler is not checking your actual conditions, so it warns that if none of your conditions are satisfied then you won't have a return value.
That's why very often programming teachers say that a good practice is to store your "return" value in a variable and then actually return it at the end of the procedure. Because of that and because it is easier to debug.
For your personal issue, you can just omit the if (hours > 5000) statement and leave it to the last else. You will obtain the same algorithm (since > 5000 is the case which will satisfy if none of the other does) and the compiler will recognize all the execution paths so it won't throw a warning.

Why is my while going in a infinity loop? How do I fix it?

I dont know why my do while is going on infinity and not showing my output which should be how many quaters, dimes ,etc has that amount of money that the user input in the system.
Scanner scan = new Scanner(System.in);
System.out.println("Enter the amount of money: ");
float dinero= scan.nextFloat();
int quaters=0;
int dimes =0;
int nickle =0;
int pennys =0;
boolean b=false;
do{
if(dinero>=0.25){
dinero=(float) (dinero-0.25);
quaters++;
}else if(dinero<0.25 && dinero>=0.10){
dinero=(float) (dinero-0.10);
dimes++;
}else if(dinero<0.10 && dinero>=0.05){
dinero=(float) (dinero-0.05);
nickle++;
}else if(dinero<0.05 && dinero<0){
dinero=(float) (dinero-0.01);
pennys++;
}else{
b=true;
}
}while(b==false);
System.out.println("Quater :"+quaters);
System.out.println("Dimes :"+dimes);
System.out.println("Nickle :"+nickle);
System.out.println("Pennys :"+pennys);
Please help i know this is a dumb question but help will be much apprishiated.
Not sure what you are trying to do but here is your problem: the last else is never executed because you covered all the possible cases in the if instructions before. Because of that, b will always be false and therefore your loop will go on forever. In which condition do you exactly want to exit this loop? Think about this and then move the instruction in the last else into the corresponding if block. Also, the if before that is not correct either. You probably meant:
if(dinero<0.5 && dinero>=0){
//do stuff
}
I fix it it was that my last condition was wrong. Also the while was wrong
else if(dinero<0.05 && dinero>=0.01){
// was the the fix for the last else if
while(dinero>0.01);
// and here is the while
change the condition of your else if statement to
else if(dinero<0.05 && dinero>0)

Delete this token (else)

ok so i was playing round with some code and adding new line as i'm learning java. i got this error "syntax error token "else" delete this token".
As im new to this could some one explain this error and what i should do, so i do not make the same mistake again.
class Years {
public static void main (String[] args){
int age = 30;
if (age <30){
System.out.println("you are young");
}else{
System.out.println("you are old ");
if (age > 1240);
}else{
System.out.println("dam son your still a bady");
if (age < 25);
{
System.out.println("You are Really old son!!");
}else{
System.out.println("you better Hide your age son!!");
}
}
}
}
You have an unconditional else block - you can't follow that with another else. So this is fine:
if (condition) {
...
} else if (otherCondition) {
...
} else {
...
}
But this isn't - because it doesn't make sense:
if (condition) {
...
} else {
...
} else {
...
}
An else block without a condition is meant to run unconditionally if the condition above it was not satisfied - in your case, the middle block is always run, so it's meaningless to have another.
Also note that you have:
if (age > 1240);
... which I suspect you didn't really intend. Likewise:
if (age < 25);
Both of these are if statements with empty bodies.
It's really unclear what you expect to achieve in each case - but I'd strongly advise you to have something like:
// List all the age boundaries in increasing order...
if (age < 25) {
...
} else if (age < 30) {
...
} else if (age < 1240) {
...
} else {
...
}
Now exactly one of those bodies will be executed.
You have a condition which doesn't make sense:
if (something) {
} else {
} else {
}
How do you expect the system to know which "else" block to use? else logically means "otherwise, do this" and effectively captures all remaining conditions. You can't do that more than once.
It looks like you've got an if statement that's in the wrong place. Try this instead:
if (age <30){
System.out.println("you are young");
}else if (age > 1240){
System.out.println("you are old ");
}else{
System.out.println("dam son your still a bady");
if (age < 25);
{
System.out.println("You are Really old son!!");
}else{
System.out.println("you better Hide your age son!!");
}
}
}
First understand how if statements work in any programming language. For example this is a good resource for you to understand if statements in java. I'm not 100% sure about what are you trying achieve by this code. But I can give you one hint. When branching, use not only else but also else if().

Extremely weird behaviour of return statement : Java

OK I have a weird problem. The code is as follows :
The method name is returnMultiPartHeading
if (recursionCount > 6 || i == list.size() - 1)
return -1;
multiPartHeading = multiPartHeading + " " + list.get(i + 1).getText();
Token token = new Token();
token.setText(multiPartHeading);
if (isHeadingType(token)) {
System.out.println("found " + multiPartHeading);
System.out.println("returning ...");
System.out.println("I is " + (i + 1));
return (i + 1);
} else {
returnMultiPartHeading(list, i + 1, multiPartHeading,
++recursionCount);
}
System.out.println("returning -1");
return -1;
}
The output is for a sample run is :
found xyz
returning...
I is 2
returning -1
why is this happening?? the if (isHeadingType(token)) evaluates to true , prints the two messages and then it totally skips the return i+1 and goes to return -1 instead. In the place I called it, I get -1 as the returned value instead of getting 2. Why is this happening?? Never saw this behaviour.
It's because in your else block, you don't actually return the result of the recursive call. You just call the method, ignore its result, and then fall through to the section below (with the return -1).
You need to change your else block to
else {
return returnMultiPartHeading(list, i + 1, multiPartHeading,
++recursionCount);
}
(assuming that your method really is called returnMultiPartHeading, which somehow doesn't sound right)
Looks like two calls are performed, the first wrote
found xyz
returning...
I is 2
and the second
returning -1
as it is a recursive method I think thats the reason
The if block is the second recursive call, which returns to the first recursive call, which was probably called by the else block. In the else block you do not return the value. Hence it skips out and returns -1.

Categories

Resources