how to combine switch and if else statements

jjason89 picture jjason89 · Jun 27, 2010 · Viewed 16.8k times · Source

I'm taking an online java class and the teacher has asked for the following: Write a menu program that ask a user for a number indicating the four basic math equations(addition, subtraction, multiplication, division). Using a if/else structure to do the required operation, ask the user for inputs and solve the equation. I am new to this, but I don't see the point of the if/else, but I guess that is irrelavent.

If I use case 1, 2, 3, 4 as below to determine the operation, how do I refference the case with a 'If statement'?

int userSelection;
double x;        
double y;        
double answer;

switch ( userSelection ) {
   case 1:
        TextIO.putln("Let's add! ");
        TextIO.putln();
        TextIO.putln("Enter the first number: ");
        x = TextIO.getlnDouble();
    TextIO.putln("Enter the second number: ");
        y = TextIO.getlnDouble();
        break;

//I thought I could use the 'If' like this

        if (case 1);  // I don't know how to refference this correctly
        answer = x + y;
        TextIO.putln( x 'plus' y 'equals' answer);

Thanks in advance!

Answer

Gert Grenander picture Gert Grenander · Jun 27, 2010

Here's the presudo code for a rewrite of a CASE statement:

IF (Case==1) THEN
  *What to do when Case==1.*
ELSE IF (Case==2) THEN
  *What to do when Case==2.*
ELSE IF (Case==3) THEN
  *What to do when Case==3.*
ELSE IF (Case==4) THEN
  *What to do when Case==4.*
END IF

You'll have to code this in Java though. :) Good luck with your assignment.