循环不破(Javascript)?

时间:2015-09-03 17:05:34

标签: javascript

我试图用一个简单的程序编写一个数字1到100的JavaScript,并用它的字母等级与美国的评分标准相比较。 (< 50 = F,60-69 = D,70 = 79 = C等......)。我遇到的问题是脚本没有注册" STOP"命令我放入它,而是将其作为无效输入。我想使用" STOP"打破循环和任何其他NaN条目以抛出错误。这是我的代码:

        var entry;
    var letterGrade;

    while(true) {
        entry = prompt("Enter number grade from 0 through 100\n" +
                       "Or enter STOP to end entries", "STOP");
        entry = parseInt(entry);

        // derive and display the letter grade
        if(isNaN(entry)){
            if(entry === "STOP"){
                letterGrade = 'Q';
            }
            else{
                letterGrade = 'N';
            }
        }

        else if(entry < 0 || entry > 100){
            letterGrade = "ERROR";
        }
        else if(entry < 60){
            letterGrade = 'F';
        }
        else if(entry > 59 && entry < 70){
            letterGrade = 'D';
        }
        else if(entry > 69 && entry < 80){
            letterGrade = 'C';
        }
        else if(entry > 79 && entry < 90){
            letterGrade = 'B';
        }
        else{
            letterGrade = 'A';
        }

        if(letterGrade == 'Q'){
            break;
        }
        else if(letterGrade == 'N'){
            alert("ERROR #002: Entry is not a number");
        }
        else if(letterGrade != "ERROR"){
            alert("Number grade = " + entry + "\n"
                + "Letter grade = " + letterGrade);
        }
        else{
            alert("ERROR #001: Invalid Entry");
        }
    }

2 个答案:

答案 0 :(得分:4)

if(isNaN(entry)){
            if(entry === "STOP"){

你不能拥有字符串值和整数。由于您将条目重新分配为int(或尝试):

 var entry;
var letterGrade;

while(true) {
    entry = prompt("Enter number grade from 0 through 100\n" +
                   "Or enter STOP to end entries", "STOP");

    // derive and display the letter grade
    if(isNaN(entry)){
        if(entry === "STOP"){
            letterGrade = 'Q';
        }
        else{
            letterGrade = 'N';
        }
    }
    entry = parseInt(entry); // parse to int here
    if(entry < 0 || entry > 100){
        letterGrade = "ERROR";
    }
    else if(entry < 60){
        letterGrade = 'F';
    }
    else if(entry > 59 && entry < 70){
        letterGrade = 'D';
    }
    else if(entry > 69 && entry < 80){
        letterGrade = 'C';
    }
    else if(entry > 79 && entry < 90){
        letterGrade = 'B';
    }
    else{
        letterGrade = 'A';
    }
    if(letterGrade == 'Q')
       break;
}

永远不会匹配。你需要重新安排事情:

{{1}}

答案 1 :(得分:0)

在这里使用递归函数会更好:

function enterGrade() {
    // All your other code above and below next line as it is above
    if(!isNan(entry)) enterGrade();
}

如果你没有得到我想要解释的内容,我可以添加更多代码。