CH26
CH26

Reputation: 63

Changing switch statement to and if-else statement

i'm revising for a test and just wondering if you could tell me if i am doing the right thing. The question asks us to convert this switch statement to and if-else statement:

switch (size) {
case 6:
price = 44.99;
break; case 7:
price = 49.99;
break; case 8:
price = 54.99;
break; case 9:
price = 59.99;
break; case 10:
price = 64.99;
break; default:
}

I've started off by doing this:

if (size==1){
System.out.println("Price is 44.99");
}
else if (size==2){
System.out.print("Price is 49.99");
}

And so on. Can someone let me know if i am doing this correctly or should i be using price instead of size and if so,why? Thank you!

Upvotes: 0

Views: 36

Answers (2)

Calvin P.
Calvin P.

Reputation: 1232

You have the right idea, but to keep your if-else statements consistent with the switch statement it would be more like

if(size==6){
    price = 44.99;
}
else if(size==7){
    price = 49.99;
else if(size==8){
    price = 54.99;
}
//etc etc

Upvotes: 1

Rahul Chaudhary
Rahul Chaudhary

Reputation: 1061

You are going on right track. According to your code it seems that you want to print prize based on size. In leader if else statement only one statement will execute so if your size is 2 it will print 44.99 else if size is three it will print 49.99 etc.

Upvotes: 0

Related Questions