chayo
chayo

Reputation: 9

convert a if statement to a swicth

Could this program be turned to a switch statement?

if (Month * Day == Year){
    System.out.println("The date is magic");
} else {
    System.out.println("The date is not magic");
}

Upvotes: 0

Views: 96

Answers (2)

Daniele
Daniele

Reputation: 724

switch(Month*Day){
 case Year:
     System.out.println("The date is magic");
     break;

  default:
    System.out.println("The date is not magic");
    break;
}

Upvotes: 1

azro
azro

Reputation: 54168

To make a switch statement, you need to constant expression like :

switch (month * day) {
    case 2000:
        System.out.println("The date is magic");
        break;
    default:
        System.out.println("The date is not magic");
}

But you cannot use a variable, you'll got constant expression required at compilation time

switch (month * day) {
    case year:

Also

  • switch is for multiple comparison, not for only one
  • please follow Java naming conventions : attributes, variables, parameters, method have to start in lowerCase

Upvotes: 4

Related Questions