Test which is easier first, which is unique value, so do this with 1 and 20, then what’s within that range is what’s left, you don’t need to test explicitly, it’s the exception, so it already falls into else
if it is not any of the numbers you have tested differently.
And take care that all conditions are bound, the else if
serves for this, the execution will fall only on one of the if
or else
, is a selection of the most suitable, the first one he enters nor tries others, the else
alone ensures that you will enter there if you do not enter any if
previous. He is like a else if (true)
.
You need to make sure you can’t give it another value, I imagine not, since the code indicated that.
var roll1 = 3;
if (roll1 == 1) {
console.log(`DESASTRE`);
} else if (roll1 == 20) {
console.log(`NORMAL`);
} else {
console.log(`FALHOU`);
}
I put in the Github for future reference.
If you can have other values then you have to change:
var roll1 = 3;
if (roll1 == 1) {
console.log(`DESASTRE`);
} else if (roll1 == 20) {
console.log(`NORMAL`);
} else if (roll1 > 1 && roll1 < 20) {
console.log(`FALHOU`);
} else {
console.log(`Deu número inválido`);
}
I put in the Github for future reference.
You should use comparison operators
x < y
andx > y
, or if you want it to be from 2 until 19 use thex >= y
andx <= y
in IF, the first IF could beif (roll1 >= 2 && roll1 <= 19){
, using && to check that both conditions are correct.– Guilherme Nascimento
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).
– Maniero