Unreachable Statement in my Public Boolean Method - java

So I'm trying to create an isValid method that verifies if a certain date is real or not (i.e. 3/31/2016 is valid, 2/29/2001 is valid since it's a leap year, 2/30/2016 is not valid)
Here is my method public boolean isValid()
`
{
//January
if (month == 1 && day <= 31) {
return true;
}
else {
return false;
}
//February
if (month == 2 && day <= 28) {
return true;
}
else {
if ((((year % 4) == 0) && ((year % 100) != 0)) || ((year % 400) == 0)) {
if (day == 29) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
//March
if (month == 3 && day <= 31) {
return true;
}
else {
return false;
}
//April
if (month == 4 && day <= 30) {
return true;
}
else {
return false;
}
//May
if (month == 5 && day <= 31) {
return true;
}
else {
return false;
}
//June
if (month == 6 && day <= 30) {
return true;
}
else {
return false;
}
//July
if (month == 7 && day <= 31) {
return true;
}
else {
return false;
}
//August
if (month == 8 && day <= 31) {
return true;
}
else {
return false;
}
//September
if (month == 9 && day <= 30) {
return true;
}
else {
return false;
}
//October
if (month == 10 && day <= 31) {
return true;
}
else {
return false;
}
//November
if (month == 11 && day <= 30) {
return true;
}
else {
return false;
}
//December
if (month == 12 && day <= 31) {
return true;
}
else {
return false;
}
}
`
Now, when I compile, it says there are unreachable statements essentially wherever it says "if". Could somebody please help? I've already tried the 'if (true) {return}' method and I can't find anything else helpful.

In your first if statement, it returns regardless of outcome, meaning all the following if statements will never be reached as if your first condition is not met it will return, and if it is, it also returns.
A fix for this is to remove all your else return false paths and string all if statements in an else if chain and then return false at the end of that.
e.g.
if(){
...
}else if(){
...
}
return false;

Your code should if elseif elseif elseif... else...
when you say if and else.. your code will end either in if or else.. henceforth other if statements are unreachable...
that is the error you are getting...change other conditions to elseif

Your code will never go to the second if statement as the else part of first(January's) will terminate your program
Your code has to be like:
if(month == 1)
{
if(day <= 31)
return true;
else
return false;
}
if(month==2)
{
----
----
}

return **statement should be last statement of any method**
else you can use variable instead of direct return statement like
public boolean isValid()
{
boolean status=false;
if(condition)
{
status=true;
}
return status;
}

Related

My code in adding condition of range 1 - 9999 is not working using switch statement

So I created LeapYearCal this on If else statement I learn switch statement I want to recreate it using switch.
Somehow my condition for leap is working, but I want to add condition like value must be in 1- 9999 only else it'll returned false. but when my code is incorrect How do I solve the problem?
public static boolean isLeapYear(int year)
{
switch ( year % 4)
{
case 0:
if (year % 100 == 0)
{
if ( (year % 400 == 0) )
{
if (year > 0)
{
if (year <= 9999)
{
return true;
}
else
return false;
}
else
return false;
}
else
return false;
}
else
return true;
default:
break;
}
return false;
I want to the output "True" if the year is Leap year and it's range 1-9999 else "False" if it is not in range regardless if its leap year
Using switch-case statement in this use-case is inappropriate. This solution is based on this code :
public static boolean isLeapYear(int year){
boolean flag = false;
if (year > 0 && year < 10000)
{
flag = false;
}
else if(year % 400 == 0)
{
flag = true;
}
else if (year % 100 == 0)
{
flag = false;
}
else if(year % 4 == 0)
{
flag = true;
}
else
{
flag = false;
}
return flag;
}

Getting a return line error for my method?

public static boolean isValidDate(int month, int day) {
if (month >= 3 && month <= 5) {
if (month == 3) {
if (day >= 1 && day <= 31) {
return true;
} else {
return false;
}
} else if (month == 4) {
if (day >= 1 && day <= 30) {
return true;
} else {
return false;
}
} else if (month == 5) {
if (day >= 1 && day <= 15) {
return true;
} else {
return false;
}
}
} else {
return false;
}
}
Get these errors:not sure how to fix them im returning everything.
BoxOffice.java:81: error: missing return statement
}
BoxOffice.java:85: error: missing return statement
}
The compiler isn't smart enough to deduce that the inner if covers every scenario in the range of the outer if. Just change
else if(month == 5) {
to
else { // month must be 5 here
shmosel's answer describes the problem and the least disruptive fix.
Personally, I'd write this as a switch, and avoid writing the long if/else statements to check the day:
switch (month) {
case 3:
return (day >= 1 && day <= 31);
case 4:
return (day >= 1 && day <= 30);
case 5:
return (day >= 1 && day <= 15);
default:
return false;
}
you need to transforme the else if (month == 5) to else ....
public static boolean isValidDate(int month, int day)
{
if (month >= 3 && month <= 5)
{
if (month == 3)
{
if (day >= 1 && day <= 31)
{
return true;
}
else
{
return false;
}
}
else if (month == 4)
{
if (day >= 1 && day <= 30)
{
return true;
}
else
{
return false;
}
}
else
{
if (day >= 1 && day <= 15)
{
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
}
Try making a boolean, and instead of returning in the if statement, change the boolean and return at the end of the method. Here is an example with your code.
public static boolean isValidDate (int month, int day) {
boolean result = true; //This must be set to a value to avoid compiler errors
if(month >= 3 && month <= 5) {
if(month == 3) {
if(day >= 1 && day <= 31) {
result = true;
}
else {
result = false;
}
}
else if(month == 4) {
if(day >= 1 && day <= 30) {
result = true;
}
else {
result = false;
}
}
else if(month == 5) {
if(day >= 1 && day <= 15) {
result = true;
}
else {
result = false;
}
}
}
else {
result = false;
}
return result;
}
Hope that helps!

Method always returns true?

I have a method that is being called to validate that an IP address is assignable. No matter what I pass to it, it is always returning true. What do I need to set the return as to get this method working properly?
public boolean checkValidIPClass(String x) {
for (int i = 0; i < 4; i++) {
try {
if (retString.equals("A")) {
if ((intParts[1] == 0) && (intParts[2] == 0) && (intParts[3] == 0))
return false;
if ((intParts[1] == 255) && (intParts[2] == 255) && (intParts[3] == 255))
return false;
}
if (retString.equals("B")) {
if ((intParts[2] == 0) && (intParts[3] == 0))
return false;
if ((intParts[2] == 255) && (intParts[3] == 255))
return false;
}
if (retString.equals("C")) {
if (intParts[3] == 0)
return false;
if (intParts[3] == 255)
return false;
}
} //ends try
catch (NumberFormatException nfe) {
return false;
} //ends catch
} //ends for
return true;
}
retString is making it to the method and is a string that was returned from another method that checks what class the IP address is and assigns it, this was verified with a print statement. Thanks!
EDIT: How has this been answered and downvoted? My question wasn't about comparing the strings, it was about the method always returning true even when I know the if statements should be catching the error and returning false?
EDIT2: Updated my code.
I don't get why you're doing a loop, but you could try this:
public boolean checkValidIPClass(String ipClass, String ipAddress)
{
if (ipClass.contentEquals("A"))
{
if (ipAddress.endsWith("0.0.0") || ipAddress.endsWith("255.255.255"))
return false;
}
else if (ipClass.contentEquals("B"))
{
if (ipAddress.endsWith("0.0") || ipAddress.endsWith("255.255"))
return false;
}
else if (ipClass.contentEquals("C"))
{
if (ipAddress.endsWith("0") || ipAddress.endsWith("255"))
return false;
}
return true;
}
Since you're just checking the ending array parts of the IP address, you don't need to break it into an array, just leave it as a string.
And keep in mind that this would only satisfy IPv4 formatted IP addresses. It will not work for IPv6 formatted addresses

Java nested ifs

Below is a small function which when given two numbers (a, b), returns true if one of the numbers is a teen-number. Returns false if both are teen. Returns false if both are not teen. I failed these test cases but I can't figure out why. Help?
(13, 99), (14, 20), and (16, 9)
public boolean loneTeen(int a, int b)
{
if(a<=19 && a>=13)
{
if(b<=19 && b>=13)
{
return false;
}
}
else if(a<=19 && a>=13)
{
return true;
}
else if(b<=19 && b>=13)
{
return true;
}
return false;
}
All three test cases will enter first if branch, they will not match inner condition and, since they already matched first branch, will not match any of else if's. So, they will all return false which is wrong.
Using a small auxiliary method can make your life much easier (and the code more readable!):
private boolean isTeen(int a) {
return a > 12 && a < 20;
}
public boolean loneTeen(int a, int b) {
if(isTeen(a) && isTeen(b) ||
!isTeen(a) && !isTeen(b)) {
return false;
}
return true;
}
First else won't be executed as you are putting the same condition on both if and else.try putting
if( a>=13 && a<=19 && b>=13 && b<=19){return false;}
else if(a>=13 && a<= 19){return true;}
else if(b<=19 && b>=13){return true;}
else return false;

Compiling Error: Missing return statement [duplicate]

This question already has answers here:
"Missing return statement" within if / for / while
(7 answers)
Closed 8 years ago.
This program plays craps with 3 different methods. I need help in playing craps but i'm required to have these 3 different methods but for some reason every time I compile I am getting this error:
CrapsAnalysis.java:48: error: missing return statement
}
^
1 error
Process javac exited with code 1
Code:
public class CrapsAnalysis
{
public static int rollDie( int n) {
return (int)(Math.random()*n) + 1 ;
}
public static int rollDice( ) {
return rollDie(6) + rollDie(6) ;
}
public static boolean playOneGame( ) {
int newDice = rollDice();
int roll = rollDice(); //first roll of the dice
int playerPoint = 0; //player point if no win or loss on first roll
if (roll == 7 || roll == 11)
return true;
else if (roll == 2 || roll == 3 || roll == 12)
return false;
else
playerPoint = roll;
do {
if (rollDice() == 7)
return false;
else if (rollDice() == playerPoint)
return true;
else
newDice = rollDice();
} while (rollDice() != playerPoint || rollDice() != 7) ;
}
}
Java must look at all execution paths. What happens if the while loop ends without returning anything? You may be logically preventing that, but the Java compiler won't do that analysis.
Provide a return statement after the end of the while loop, or throw some kind of an Exception (IllegalStateException?) if the code really shouldn't ever make it there.
You can add the last return statement after your code like this:
public static boolean playOneGame() {
int newDice = rollDice();
int roll = rollDice(); // first roll of the dice
int playerPoint = 0; // player point if no win or loss on first roll
if (roll == 7 || roll == 11)
return true;
else if (roll == 2 || roll == 3 || roll == 12)
return false;
else
playerPoint = roll;
do {
if (rollDice() == 7)
return false;
else if (rollDice() == playerPoint)
return true;
else
newDice = rollDice();
} while (rollDice() != playerPoint || rollDice() != 7);
return false;
}
It will make it compile and your code will still work.
you only return statements are inside the body of an if block.
The compiler doesn't know if any of those if blocks will ever be reached, so it's giving you an error.
You might want to have a default return statement at the end
} while (rollDice() != playerPoint || rollDice() != 7) ;
return false;
}
I'm assuming that if that default return statement ever actually gets executed, than it's an error state, and you should react accordingly.
You are missing a return in your while block:
public static boolean playOneGame( ) {
int newDice = rollDice();
int roll = rollDice(); //first roll of the dice
int playerPoint = 0; //player point if no win or loss on first roll
if (roll == 7 || roll == 11)
return true;
else if (roll == 2 || roll == 3 || roll == 12)
return false;
else
playerPoint = roll;
do {
if (rollDice() == 7)
return false;
else if (rollDice() == playerPoint)
return true;
else
newDice = rollDice();
} while (rollDice() != playerPoint || rollDice() != 7)
**// You are missing a return statement here.**;
public static boolean playOneGame( ) {
int newDice = rollDice();
int roll = rollDice(); //first roll of the dice
int playerPoint = 0; //player point if no win or loss on first roll
if (roll == 7 || roll == 11)
return true;
else if (roll == 2 || roll == 3 || roll == 12)
return false;
else
playerPoint = roll;
do {
if (rollDice() == 7)
return false;
else if (rollDice() == playerPoint)
return true;
else
newDice = rollDice();
} while (rollDice() != playerPoint || rollDice() != 7) ;
return SOMETHING HERE;
}
You should look into consistent code formatting. Not only for us, but for yourself as well so when you look at this code after a few weeks you can still read it.
When you have to add return make sure you add return for every possible execution path of add a default return statement. You program is missing both of them
public class CrapsAnalysis
{
public static int rollDie( int n) {
return (int)(Math.random()*n) + 1 ;
}
public static int rollDice( ) {
return rollDie(6) + rollDie(6) ;
}
public static boolean playOneGame( ) {
int newDice = rollDice();
int roll = rollDice(); //first roll of the dice
int playerPoint = 0; //player point if no win or loss on first roll
if (roll == 7 || roll == 11)
return true;<--- Works
else if (roll == 2 || roll == 3 || roll == 12)
return false;<--- Works
else
playerPoint = roll;
do {
if (rollDice() == 7)
return false;<--- Works
else if (rollDice() == playerPoint)
return true;<--- Works
else
newDice = rollDice();
} while (rollDice() != playerPoint || rollDice() != 7) ;
//No return here. You need to add a default return if none of the conditions above satisfies
}
}
Here is a very stripped down version of your code:
public static boolean playOneGame()
{
if(condition1 == true)
{
//code1
return true;
}
else if(condition2 == true)
{
//code2
return false;
}
else
{
//code3
}
//code4
}
If condition1 or condition2 is true, playOneGame() will return either true of false. However, if condition1 and condition2, are both false, the only code that will run is code3. code3 does not contain a return statement, so it is theoretically possible that playOneGame() will not return anything. You know that condition1 and condition2 will never both be false, but the java compiler does not, so it throws a compiler error. If it did not throw a compiler error and condition1 and condition2 somehow both became false, it would throw a runtime error. Runtime errors are a lot harder to debug than compiler errors, so the compiler is doing you a favor by throwing an easy-to-fix error.
To fix the missing return statement, add a return statement to code3 or code4.
After your while loop you need a return statement, because the if/else statements may or may not be executed. If none of them execute, you have no return. Therefore, you need to ensure that there will be at least one return statement that can always be executed.
public static boolean playOneGame( ) {
int newDice = rollDice();
int roll = rollDice(); //first roll of the dice
int playerPoint = 0; //player point if no win or loss on first roll
if (roll == 7 || roll == 11)
return true;
else if (roll == 2 || roll == 3 || roll == 12)
return false;
else
playerPoint = roll;
do {
if (rollDice() == 7)
return false;
else if (rollDice() == playerPoint)
return true;
else
newDice = rollDice();
} while (rollDice() != playerPoint || rollDice() != 7) ;
return false;
}
Also, for clarity, I rearranged your if/else statements so it is easier to read. You might want to get into the habit of doing this as well so that others can have an easier time understanding your code.

Categories

Resources