0
  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?

4
Contributors
6
Replies
8
Views
4 Years
Discussion Span
Last Post by stultuske
0

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.

0
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...

0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.