Javascript窗口提示

时间:2012-12-13 04:28:23

标签: javascript

var target=10;
var totalGuess=0;
var input = window.prompt('Enter a number between 1 and 100: ');  
var guess = parseInt(input);  
  do  
    {  
        totalGuess++;  
        if (guess < target)  
        {  
            window.prompt("Too low! Guess Again!");  
        }  
        if (guess > target)  
        {  
            window.prompt("Too High! Guess Again!");  
        }  
        if (guess == target)  
        {  
            alert("Thats right! It took you " +totalGuess +" tries to get it right!"); 
            break;
        }  

    } while (guess != target );  

我正在尝试检查用户输入的数字是高还是低,但此程序只检查一个语句然后停止。

4 个答案:

答案 0 :(得分:1)

您需要移动这两行:

var input = window.prompt('Enter a number between 1 and 100: ');  
var guess = parseInt(input);

到do语句的内部,以便反复提示用户,直到他们正确猜出。

答案 1 :(得分:0)

var target=10;
var totalGuess=0;
var input = window.prompt('Enter a number between 1 and 100: ');  
var guess = parseInt(input);  
do  
    {  

        guess = parseInt(input);  
        totalGuess++;  

        if (guess < target)  
        {  
           input = window.prompt("Too low! Guess Again!");  
        }  
        if (guess > target)  
        {  
           input = window.prompt("Too High! Guess Again!");  
        }  
        if (guess == target)  
        {  
            alert("Thats right! It took you " +totalGuess +" tries to get it right!"); 
        break;
        }  


    } while (guess != target );  

答案 2 :(得分:0)

试试这个

检查在http://jsfiddle.net/9mQ2b/14/

工作

您没有重新初始化Guess变量,因此每次都可以检查条件

<!DOCTYPE html>
<html>
<body>
<script>

var target=10;
var totalGuess=0;
var input = window.prompt('Enter a number between 1 and 100: ');  
var guess = parseInt(input);  
do  
    {  


        totalGuess++;  

        if (guess < target)  
        {  
 guess = parseInt (window.prompt("Too low! Guess Again!"));  
        }  
        if (guess > target)  
        {  
 guess = parseInt (window.prompt("Too High! Guess Again!"));  
        }  
        if (guess == target)  
        {  
            alert("Thats right! It took you " +totalGuess +" tries to get it right!"); 
        break;
        }  


    } while (guess != target ); 
</script>
</body>
</html>

答案 3 :(得分:0)

问题是只有你的第一个输入被输入程序。您的后续输入值将被忽略。试试这个。

    if (guess < target)  
        {  
                input = window.prompt("Too low! Guess Again!");
                guess = parseInt(input);   
        }  
        if (guess > target)  
        {  
                input = window.prompt("Too High! Guess Again!"); 
                guess = parseInt(input); 
        }  
        if (guess == target)  
        {  
                alert("Thats right! It took you " +totalGuess +" tries to get it right!"); 
        break;
  }