javascript - 我的while循环哪里出错了?

我对循环的工作方式很陌生。如果输入为 N,我希望循环结束,因为“你玩我的世界吗?”如果用户输入Y,用户输入多少小时后,我需要它继续计算部分并让它显示。我的程序不这样做。我不确定为什么它继续循环并且不继续下一部分。

//Variables
var hours;
var total;
var keepLooping = "Y";
var askingAQuestion = true;
userInput = "";

//calculation and conversion
total = hours * 7;
hours = Number(hours);

// Get the input from the user
function myFunction() {
    while (keepLooping === "Y") {
        userInput = prompt("Do you play minecraft?" + " Y or N");
        if (userInput === "N") {
            askingAQuestion = false;
            document.write("You should download the free trial!");
        } else if (userInput === "Y") {
            document.write("That's great!");
            hours = prompt("how many hours a day do you play minecraft?")
        } else if (hours >= 3) {
            document.write("if You play minecraft" + hours + "a day");
            document.write("You play minecraft" + total + "hours a week!");
        }

    }
}

myFunction();

回答1

满足条件时更改keepLooping value

//Variables
var hours;
var total;
var keepLooping = "Y";
var askingAQuestion = true;
userInput = "";

//calculation and conversion
total = hours * 7;
hours = Number(hours);

// Get the input from the user
function myFunction() {
    while (keepLooping === "Y") {
        userInput = prompt("Do you play minecraft?" + " Y or N");
        if (userInput === "N") {
            askingAQuestion = false;
            keepLooping =  "N";
            document.write("You should download the free trial!");
        } else if (userInput === "Y") {
            document.write("That's great!");
            hours = prompt("how many hours a day do you play minecraft?")
        } else if (hours >= 3) {
            document.write("if You play minecraft" + hours + "a day");
            document.write("You play minecraft" + total + "hours a week!");
        }

    }
}

myFunction();

相似文章

随机推荐

最新文章