-1

I am learning switch statements. I write some codes like this:

String computerMove;
switch ( (int)(3*Math.random()) ){
   case 0:
      computerMove = "Rock";
      break;
   case 1:
      computerMove = "Paper";
      break;
   case 2:
      computerMove = "Scissors";
      break;


}
System.out.println("The computer`s move is " + computerMove);

I was asked to add "case" or "default" or '}' after I compiled my code. I tried to change code "case 2: " to "default:", it worked. I could not understand why it worked? It seemed that my code included all possible values.

KMING
  • 11
  • 5

1 Answers1

0

When you use switch with an int, the compiler will just check that all case options are all int and are unique, but it will not check what is the possible range of this int. You can even add case 532:, it will still work, because the compiler just verifies that your case has an int type

Vincent
  • 3,945
  • 3
  • 13
  • 25
  • Did you mean that the compiler just examines the type of all case options without actual value? Is it better to use "default" always? – KMING Nov 21 '19 at 02:09
  • Maybe. I would leave your explicit 0, 1, 2 cases as explicitly coded. I might consider adding a "default:" which reports in some way that something unexpected has happened (in your case, that the expression is less than 0 or greater than 2). It "should never happen" but it's useful to detect it quickly when (ok: 'if') it does. This is kind of overkill in your simple example, but in more complicated program it might be valuable. –  Nov 21 '19 at 02:17
  • @KMING yes this is what I'm saying, and yes it's better to always have default, even when it's supposed to never happen, you can add "default" with System.out.println("This was never supposed to happen") – Vincent Nov 21 '19 at 02:37