# Using variables in switch statement case clauses

• May 19th, 2014, 04:48 PM
kunimaro15689
Using variables in switch statement case clauses
I am stuck with two switch statements that I feel I am close to achieving. My first switch statement is to generate random mathematical operators for the math questions in the game (generated randomly) My second switch statement is to determines which action the system will take upon the correct or incorrect answer. For the first switch statement I have a variable called num. Num is a random integer. I have an operator mapped to each outcome of num. I may know the solution to fix this. In my second switch statement I am trying to use the variable answer as a variable in the first case but do not know how. Advice?

Code java:

```package pkgnew;   import java.util.Scanner; import java.util.Random;   public class New {   public static void main(String args[]) {     //Declare and construct variables Random randomnum = new Random(); int fnum, snum, answer; int mathnumber = randomnum.nextInt(20); int newnumber = randomnum.nextInt(20); int num = randomnum.nextInt(4); char operator;     //Switch statement for random operator switch (num) { case 1: operator = '+'; break; case 2: operator = '-'; break; case 3: operator = '*'; break; case 4: operator = '/'; break; }     //Declare and construct variables of math problem fnum = mathnumber; snum = newnumber; answer = fnum + snum;   //Math problem 10x loop     //Output of math problem System.out.print(fnum); System.out.print(num); System.out.println(snum);   //User input Scanner serena = new Scanner(System.in); int userAnswer = serena.nextInt();   //Switch statement for corect/incorrect answer switch (answer) { case answer: System.out.println("correct!"); break; default: System.out.print("incorrect! The correct answer is:"); System.out.println(answer); break; }   } }```
• May 19th, 2014, 04:58 PM
Cornix
Re: Using variables in switch statement case clauses
The cases in a switch statement must be constants and not variables. If you want to use variables you have to use an if-elseif block.
• May 19th, 2014, 06:21 PM
kunimaro15689
Re: Using variables in switch statement case clauses
That is fine. I had an if else block before and it worked. I am just practicing and seeing what I can and cannot do. My primary concern is generating random math operators to appear in the question.