public String getCurrentDay()
   {
       if(day.getValue() == 0) {
          return "Sunday";
       }   
       if(day.getValue() == 1) {
          return "Monday";    
       }
       if(day.getValue() == 2) {
          return "Tuesday";
       }    
       if(day.getValue() == 3) {
          return "Wednesday";
       }   
       if(day.getValue() == 4) {
          return "Thursday";
       }
       if(day.getValue() == 5) {
          return "Friday";
       }
       if(day.getValue() == 6) {
          return "Saturday";
       }    
       return "null";
   }

How do I make this into a switch statement?

Recommended Answers

All 6 Replies

you don't have to read a lot to understand a switch statement. It works like this:

switch(variable)
{
case 1:
    //do something
    break;
case 2:
    //do something
    break;
case 3:
    //do something
    break;
//...
default://in case it's an unknown case
    //do something
    break;
}

In your case, break;'s are not necessary. Break is used to go to the first line after the switch.

public String getCurrentDay()
    {
   switch(day) {

        case 0: dayString = "Sunday";
                break; 
        case 1: dayString = "Monday"; 
                break;
        case 2: daysString = "Tuesday";
                break;
        case 3: dayString = "Wednesday";
                break;
        case 4: dayString = "Thursday";
                break;
        case 5: dayString = "Friday";
                break; 
        case 6: dayString = "Saturday";        
    }
   }  

I tried to compile this and an error message said that the varible (day) is an incompatible type, what do I do?

I am taking an introductory software development course. Please understand...

ok the variable is ("day")

@ SuperManofBC,
day should be integer variable,
check this link

Hey thanks that helped..

Anand01: it's maybe a bit late for this response, but anyway: in this example it should indeed be an int, but starting from java 7 it is possible to use a String variable as value in a Switch, there's an example in the link you've posted.
so it just depends on what JDK is installed and what the goal is, whether it should be an int or not.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.