2016-12-06 6 views
1

두 개의 숫자 (x와 y)를 무작위로 생성하고 사용자에게 곱하기를 요청하는 프로그램이 있습니다. 일단 그들이 번식하면, 그것이 옳은지 잘못되었는지를 알려줍니다. 내가 문제를 겪고있는 것은 그들이 정확한 답을 얻으면 새로운 숫자를 만들어야한다는 것입니다. 프로그램이 그 기능을 다시 수행하게하는 방법을 모르겠습니다. 또한 그들이 옳은지 또는 잘못되었는지에 상관없이 대답 필드를 정리해야합니다. 감사!JavaScript가 정확한 답변이면 새 문자열을 생성하십시오.

var x, y; // global variables for randomly generated numbers 
var correct = ['Very good!', 'Excellent!', 'Correct - Nice work!', 'Correct - Keep up the good work!']; 
var incorrect = ['No. please try again.', 'Wrong. Try once more.', 'Incorrect - Dont give up!', 'No - Keep trying.']; 

// getting two random numbers between 1-12 then assigning them to x and y 

function generateNumbers() { 
    function aNumber() { 
     return Math.floor((Math.random() * 12) + 1); 
    } 
    x = aNumber(); 
    y = aNumber(); 
} 

// generating the question that will be used with the random numbers x and y 
function genQuestion() { 
    generateNumbers(); 
    document.getElementById('question').value = x + " times " + y; 
} 

// function that is performed when the button "check answer" is clicked. It will generate one of 4 answers depending 
//if it's right or wrong and will add 1 to the value of total. If it's incorrect it won't add anything 
function buttonPressed() { 
    var correctans = correct[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's correct 
    var incorrectans = incorrect[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's incorrect 
    var answer = document.getElementById('answer').value; 

    if (answer == x * y) // correct 
     { 
      function genQuestion() { 
       generateNumbers(); 
       document.getElementById('question').value = x + " times " + y; 
      } 
      window.alert(correctans); 
      var total = document.getElementById('total').value++; 
     } 
    else {    // incorrect 
     window.alert(incorrectans); 
    } 
} 

답변

1

genQuestion 함수를 호출하지 않고 재정의하는 것이 의미가 없습니다.

// function that is performed when the button "check answer" is clicked. It will generate one of 4 answers depending 
//if it's right or wrong and will add 1 to the value of total. If it's incorrect it won't add anything 
function buttonPressed() { 
    var correctans = correct[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's correct 
    var incorrectans = incorrect[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's incorrect 
    var answer = document.getElementById('answer').value; 

    if (answer == x * y) // correct 
     { 
      //call genQuestion to create new question 
      genQuestion(); 
      window.alert(correctans); 
      var total = parseInt(document.getElementById('total').value)++; 
     } 
    else {    // incorrect 
     window.alert(incorrectans); 
    } 
    //clear 'answer' field 
    document.getElementById('answer').value = ''; 
} 
+0

많은 도움을 주셔서 감사합니다. – rozak