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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With