jeudi 30 avril 2020

Javascript, how to write a while loop inside a if-else loop

Can anyone tell me what is wrong with my code. It seems like the after continue; it still loop over the same block even I input the largest number (i.e.10) here it still want me to input larger number

// 1) Generate a random integer from 0 to 10 (reference: Math.random())
const RanNum = Math.floor(Math.random() * Math.floor(11))
console.log(RanNum)

// 2) Ask the user input (reference: prompt())

let userInput = prompt(`Give me a  number`)
const userInputInt = parseInt(userInput)
console.log(userInput) 
console.log(typeof(userInput))
console.log(userInputInt)
console.log(typeof(userInputInt))


if(isNaN(userInput)){
    prompt(`Give me a freaking number`)
}else{
    let x = 0;
    while (x < 4) {
        console.log('hi')
        console.log(userInputInt)
        console.log(RanNum)

        if (userInputInt == RanNum) {
            console.log(`win`)
            prompt('YOU GOT IT MAN')
            break;
        }
        else if (userInputInt < RanNum) {
            x = x+1 ;
            prompt('Larger please')
            continue;

        }
        else if (userInputInt > RanNum) {
            x= x+1
            prompt('Smaller please')
            continue;

        }

    }
    if(x > 3){alert('More than 3 times')}

}

However, this one work fine. Can someone point to me whats wrong???

// Guess the number

const randomNumber = Math.floor(Math.random() * 11);

let trials = 0;

while(trials < 4){
    const guess= parseInt(prompt("Give me a number(0-10)!"));
    if(isNaN(guess)){
        alert("You are not inputing a number");
        // Works for while-loop, for-loop, do-while loop
        continue;
    }
    trials++;
    if(guess === randomNumber){
        // Equal
        alert("You win!!");
        // If the player wins, terminate the game
        // Works for while-loop, for-loop, do-while loop
        break;
    }else{
        // Unequal
        if(guess > randomNumber){
            alert("Too large!");
        }else{
            alert("Too small");
        }
    }
}

if(trials > 3){
    alert("You loses");
}

Aucun commentaire:

Enregistrer un commentaire