Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to make a magic eightball and my switch statement isn't working

I've just started doing JS and wanted to make a magic Eightball.

let randomNumber = Math.floor(Math.random() * 8)
let eightball = '';

switch (randomNumber){
  case '0' :
    eightball = 'It is certain';
    break;
  case '1' :
    eightball = 'It is decidedly so';
    break;
  case '2' :
    eightball = 'Repy is hazy try again';
    break
  case '3' :
    eightball = 'Cannot predict now';
    break;
  case '4' :
    eightball = 'Do not count on it';
    break;
  case '5' :
    eightball = 'My sources say no';
    break;
  case '6' :
    eightball = 'Outlook not so good';
    break;
  case '7' :
    eightball = 'Signs point to yes';
    break;
  default :
    eightball = 'yes';
    break;
}

console.log(`The magic eightball said : ${eightball}.`);

however it only ever outputs the default. If I take the default out it doesn't output anything. I know it's probably a syntax error but I still can't figure it out.

like image 399
Nikcross Avatar asked Nov 27 '25 19:11

Nikcross


1 Answers

Your randomNumber variable is a number, and the switch statement is comparing it to strings.

Here is a fixed version:

let randomNumber = Math.floor(Math.random() * 8)
let eightball = '';

switch (randomNumber){
  case 0:
    eightball = 'It is certain';
    break;
  case 1:
    eightball = 'It is decidedly so';
    break;
  case 2:
    eightball = 'Repy is hazy try again';
    break
  case 3:
    eightball = 'Cannot predict now';
    break;
  case 4:
    eightball = 'Do not count on it';
    break;
  case 5:
    eightball = 'My sources say no';
    break;
  case 6:
    eightball = 'Outlook not so good';
    break;
  case 7:
    eightball = 'Signs point to yes';
    break;
  default:
    eightball = 'yes';
    break;
}

console.log(`The magic eightball said : ${eightball}.`);

By the way, Math.random() is always less than 1, so randomNumber will never equal 8, and the default of the switch will never be reached.

like image 149
Byron Avatar answered Nov 30 '25 08:11

Byron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!