Why does my if-chain not stop? [duplicate] - java

This question already has answers here:
If statement seems to be skipping to else
(5 answers)
Closed 5 years ago.
I was running a program with my students today and we came to a method that asked them to create conditional statements that prompts the user on the day of week after an input of 1 - 7 which correspond to Sunday to Saturday.
A student came up with the code below which prints out "Thursday", but it also prints out the else statement. I cannot figure out why it does not stop at d == 5. But when I changed the method to return a String and had each if statement return a String like "Sunday" it worked. The code is below. Why does the program not stop for the void method, but stop for the String method?
public static void dayOfWeek(int d) //This did not stop at d == 5.
{
if (d == 1)
{
System.out.println("Sunday");
}
if (d == 2)
{
System.out.println("Monday");
}
if (d == 3)
{
System.out.println("Tuesday");
}
if (d == 4)
{
System.out.println("Wednesday");
}
if (d == 5)
{
System.out.println("Thursday");
}
if (d == 6)
{
System.out.println("Friday");
}
if (d == 7)
{
System.out.println("Saturday");
}
else
{
System.out.println("Oops! Number must be between 1 and 7");
}
}
public static String dayOfWeek(int d) //This worked at d == 5.
{
if (d == 1)
{
return "Sunday";
}
if (d == 2)
{
return "Monday";
}
if (d == 3)
{
return "Tuesday";
}
if (d == 4)
{
return "Wednesday";
}
if (d == 5)
{
return "Thursday";
}
if (d == 6)
{
return "Friday";
}
if (d == 7)
{
return "Saturday";
}
else
{
return "Oops! Number must be between 1 and 7";
}
}

The point is that there is a difference between an else if and and if when used in consecutive conditionals. In your situation
if (a) { .. }
if (b) { .. }
else { .. }
the if (a) conditional is not related in any way to if (b). Both conditions are evaluated independently and their body executed accordingly. So the else condition is attached to the second conditional only and will be executed when b is false regardless of what's been executed before.
In any case you'd better use a String[] for that situation, eg:
private static final String[] days = { "Sunday", "Monday" ... };
public static String dayOfWeek(int d) {
if (d >= 1 && d <= 7)
return days[d-1];
else
throw new IllegalArgumentException("Day of the week out of bounds!");
}

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!

Unreachable Statement in my Public Boolean Method

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

simple java calculator help needed [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
So basically, I'm trying to create a simple java calculator for the following functions but it seems my functions are not executing the way they're supposed (i.e. + not adding, - not subtracting). Would appreciate some help :)
if (ope == "+") {
//add
} else if (ope == "-") {
//subtract
} else if (ope == "*") {
//multiply
} else if (ope == "/") {
//divide
}
}
Incorrect String comparison, instead of:
if (ope == "+") {
} else if (ope == "-") {
} else if (ope == "*") {
} else if (ope == "/") {
you should have:
if ("+".equals(ope)) {
} else if ("-".equals(ope)) {
} else if ("*".equals(ope)) {
} else if ("/".equals(ope)) {
In Java SE 7 and later, you can use a String object in the switch statement's expression. More info
if(ope != null)
{
switch(ope)
{
case "+" : do1(); break;
case "-" : do2(); break;
case "*" : do3(); break;
case "/" : do4(); break;
default : doDefault(); break;
}
}
More info about String comparison

Improve Java code: too many if's

I have several cases and I am just using simple if ... if else blocks.
How can I reduce the number of if statements in this code?
Perhaps I could use a lookup table, but I am not sure how to implement it in Java.
private int transition(char current, int state)
{
if(state == 0)
{
if(current == 'b')
{
return 1;
}
else
return 0;
}
if(state == 1)
{
if(current == 'a')
{
return 2;
}
else
return 0;
}
if(state == 2)
{
if(current == 's')
{
return 3;
}
else
return 0;
}
if(state == 3)
{
if(current == 'e')
{
return 3;
}
if(current == 'b')
{
return 4;
}
else
return 0;
}
if(state == 4)
{
if(current == 'a')
{
return 5;
}
else
return 0;
}
if(state == 5)
{
if(current == 'l')
{
return 6;
}
else
return 0;
}
else
return 0;
}
What you're trying to do looks very much like a finite state machine, and these are usually implemented with the help of a transition table. Once you set up the table, it's simply a matter of indexing to the position you want to get the return value. Assuming your return values are all less than 256, you can use a 2D byte array:
byte table[][] = new byte[NUM_STATES][NUM_CHARACTERS];
// Populate the non-zero entries of the table
table[0]['b'] = 1;
table[1]['a'] = 2;
// etc...
private int transition(char current, int state) {
return table[state][current];
}
Well, you can easily utilize hash. Simple and clean.
// declare hashtable
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("0-b", 1);
map.put("1-a", 2);
map.put("2-s", 3);
...
// get result
Integer result = map.get(state + "-" + current);
// change null (nothing found) to zero
return result == null ? 0 : result;
consider interfaces + enums:
interface State<T>
{
public void State<T> step(T input);
}
enum MyState implements State<Character> {
STATE0(0) { #Override public void MyState step(Character c) { return c == 'b' ? STATE1 : STATE0; }},
STATE1(1) { #Override public void MyState step(Character c) { return c == 'a' ? STATE2 : STATE0; }},
/* rest of states here */
final private int value;
MyState(int value) { this.value = value; }
public int getValue() { return this.value; }
}
class SomeClass
{
public MyState currentState = STATE0;
public void step(char input)
{
this.currentState = this.currentState.step(input);
}
}
i switch statement would be best here:
private int transition(char current, int state)
{
switch(state)
{
case 0:
return current == 'b' ? 1 : 0;
case 1:
return current == 'a' ? 2 : 0;
case 2:
return current == 's' ? 3 : 0;
case 3:
return current == 'e' ? 3 : (current == 'b' ? 4 : 0);
case 4:
return current == 'a' ? 5 : 0;
case 5:
return current == 'l' ? 6 : 0;
default:
return 0;
}
}
And a note, theres only 5 if statements there checking pure intergers, this is not exactly an overhead.
Looks like you need a better abstraction for a finite state machine. Think about a class that encapsulates what you want in a better way so you can extend it by configuration rather than modifying code.
If this code is about to be expanded over the time, why not use a state machine? Each state will return the next state based on the character it receives. Maybe it's an overkill for this code, but it'll be a lot easier to maintain, expand & read.
Use switch statement for the outer if chain:
switch (state) {
case 0: <code> ; break;
case 1: <code> ; break;
case 2: <code> ; break;
<etc>
default: return 0; break;
}

Categories

Resources