Search code examples
javaunreachable-statement

Complex Conditionals and Unreachable Statements


I am very new to Java and am having some trouble. I feel like this an easy fix. Basically, I am looking to return a statement if two criteria are met. Below is my attached code.

boolean Windy = false;

if (Windy = true) 
  return "It is Windy";
else 
  return "Not Windy";

if (temperature < 30);
{return "Too Windy or Cold! Enjoy watching the weather through the window";

Additional errors are being thrown after I try to alter the script, claiming a return statement is required.


Solution

  • Your code contains several mistakes:

    1. The = in Windy = true should be a == instead. = is to assign something, and == is to check for equality.
    2. Because your first if (Windy = true) return "It is Windy"; else return "Not Windy"; will always return one of the two, the rest of your code below it is unreachable and will never be executed.
    3. Even if it was reachable, the trailing semi-colon at the if (temperature < 30); should be removed.
    4. The {}-block inside your method isn't necessary.

    I think this is what you are looking for with your code:

    boolean windy = false;
    
    if(windy){
      return "It is Windy";
    } else if(temperature < 30){
      return "Too Windy or Cold! Enjoy watching the weather through the window";
    } else{
      return "Not Windy";
    }
    

    Of course, setting windy to false hard-coded kinda makes the first check impossible to reach as well. But I assume it's just your example code and in your actual code you retrieve the windy as class variable or method parameter.

    In addition, since windy itself is a boolean, the == true is redundant and just if(windy) would be enough.

    PS: Variable names in Java are best practice to be camelCase, so use windy instead of Windy in this case.
    I've also added the brackets around the if/else-if/else statements. They aren't required and you can leave them out if you really prefer, but it's easier to modify code without making errors later on.