0

I am developing a trivia program, in which a user gets asked a question at random, and has to enter an answer. The program is telling the user whether they got the question right, and at the end alerts them of their score. Here is my code:

function askQuestion() {
    score = 0
    for (let step = 0; step < 5; step++) {
        rando = Math.floor(Math.random() * 5)+1;
        switch(rando) {
            case 1:
                var q1 = prompt("Who won the first ever international soccer World Cup? Please write the first letter in capital, and the following ones in lowercase")
                if (q1 == "George Washington") {
                    alert("Correct!")
                    score = score + 1
                } else {
                    alert("Sorry you are incorrect")
                }
                break;
            case 2:
                var q2 = prompt("What is a theorem in math for finding a side in a right triangle, knowing 2 others? Please write the both words in capital")
                if (q2 == "Pythagorean Theorem") {
                    alert("Correct!")
                    score = score + 1
                } else {
                    alert("Sorry you are incorrect")
                }
                break;
            case 3:
                var q3 = prompt("Who is the first human ever in space? Please write the full name in capital, and the following ones in lowercase")
                if (q3 == "Yuri Gagarin") {
                    alert("Correct!")
                    score = score + 1
                } else {
                    alert("Sorry you are incorrect")
                }
                break;
            case 4:
                var q4 = prompt("Who is the first president of the United States? Please write the full name in capital, and the following ones in lowercase")
                if (q4 == "George Washington") {
                    alert("Correct!")
                    score = score + 1
                } else {
                    alert("Sorry you are incorrect")
                }
                break;
            case 5:
                var q5 = prompt("In what country were the Olympics invented? Please write the first letter in capital, and the following ones in lowercase")
                if (q5 == "Greece") {
                    alert("Correct!")
                    score = score + 1
                } else {
                    alert("Sorry you are incorrect")
                }
                break;
            case 6:
                var q6 = prompt("What is the capital of France? Please capitalize the first letter")
                if (q6 == "France") {
                    alert("Correct!")
                    score = score + 1
                } else {
                    alert("Sorry you are incorrect")
                }
                break;
            case 7:
                var q7 = prompt("What is the most purchased video game of all time? Please capitalize the first letter")
                if (q7 == "Minecraft") {
                    alert("Correct!")
                    score = score + 1
                } else {
                    alert("Sorry you are incorrect")
                }
                break;
            case 8:
                var q8 = prompt("What is the most watched television brodcast ever? Please write the full name, capitlizing the abbreviation of the organization it is created by, and then the name too.")
                if (q8 == "UEFA Euro 2020") {
                    alert("Correct!")
                    score = score + 1
                } else {
                    alert("Sorry you are incorrect")
                }
                break;
            case 9:
                var q9 = prompt("What is the most popular board game in the world? Please capitalize")
                if (q9 == "Chess") {
                    alert("Correct!")
                    score = score + 1
                } else {
                    alert("Sorry you are incorrect")
                }
                break;
            case 10:
                var q10 = prompt("What year was the U.S. Declaration of Independence written and ratified?")
                if (q10 == "1776") {
                    alert("Correct!")
                    score = score + 1
                } else {
                    alert("Sorry you are incorrect")
                }
                break;
            default:
                alert("This is impossible")
                break;
        }   
    }
    alert("Thanks for playing! Your score is " + score + " out of 5!")
}
askQuestion()

I am unable to find a way to not have the program ask a question twice using an array. May someone please help me? Thank you.

Aykhan
  • 31
  • 9
  • Does this answer your question? [How to efficiently randomly select array item without repeats?](https://stackoverflow.com/questions/17891173/how-to-efficiently-randomly-select-array-item-without-repeats) – pilchard Jan 03 '22 at 00:41

2 Answers2

3

Here's a hint, ditch the switch. Have an array of objects with all the questions and answers, like:

const data: [
  { question: "Who?", answer: "Him" },
  { question: "What?", answer: "That" },
  { question: "Where?", answer: "There" }
]

Ditch the for loop, use a while loop, and reuse the logic. All you need is the random index

while ( data.length > 0 ) {
   let randomIndex = Math.floor(Math.random() * data.length) + 1;

   var userAnswer = prompt(data[randomIndex].question)

   if (userAnswer === data[randomIndex].answer) {
       alert("Correct!")
       score = score + 1
   } else {
       alert("Sorry you are incorrect")
   }
   data.splice(randomIndex, 1); // remove that question and answer set
}
   
Dan Oswalt
  • 2,201
  • 2
  • 14
  • 24
  • cool, mind Emiel Zuurbier's suggestion to use .toLowerCase() on your `userAnswer` input, else the user will think `george washington` is wrong. – Dan Oswalt Jan 03 '22 at 01:04
  • 2
    The first sentence of the answer rhymes. +1 for that. – Capt 171 Jan 03 '22 at 01:31
  • Hey, @DanOswalt I'm sorry for bothering you again, but I have a slight problem. If an answer is entered incorrectly, the loop goes on and works perfectly. However, if an answer is correct, the program instantly breaks and no more questions are asked. Is there any way you may help? Thank you. – Aykhan Jan 05 '22 at 00:21
2

You could create an array of all of your questions paired with their answers like here in the example below.

Important: define these questions outside of your askQuestions function as you only want them defined once when the page loads.

const questions = [
  {
    question: 'Who won the first ever international soccer World Cup? Please write the first letter in capital, and the following ones in lowercase',
    answer: 'george washington'
  },
  {
    question: 'What is a theorem in math for finding a side in a right triangle, knowing 2 others? Please write the both words in capital',
    answer: 'pythagorean theorem'
  },
  {
    ...
  },
  ...
];

Then select a random question from the array. This is done similar to your current method.

const randomIndex = Math.floor(Math.random() * questions.length);
const randomQuestion = questions[randomIndex];

From here you can access both the question and answer properties that are in the question object. You can apply the same logic as you already did to ask the question and to check the answer.

Now if an answer is correct, then you don't want to ask that question again. You can do this by removing the question form our questions array after a good answer has been given.

With the .splice method on the question array we can remove a single item from the array based on an index. We already got the index stored in randomIndex and we'll need it to remove the question from the array.

The question cannot be asked again until the page has been refreshed.

const answer = prompt(randomQuestion.question);
if (answer.toLowerCase() === randomQuestion.answer) {
  score++;

  // Remove 1 item starting from the randomIndex value.
  questions.splice(randomIndex, 1);

  alert('Correct!');
} else {
  alert('Incorrect!')
}

As an addition I would suggest that you define your answers all in lowercase and transform the answer of the user also to lowercase and then compare them. You can do this with the .toLowerCase() method on the string that prompt returns.

Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32
  • 1
    Actually better off using `String#localeCompare()` with `{sensitivity: 'base'}` (or `'accent'` if it's relevant) and possibly `ignorePunctuation` options set. see: [How to do case insensitive string comparison?](https://stackoverflow.com/questions/2140627/how-to-do-case-insensitive-string-comparison). This allows the answer to be capitalized correctly for display purposes without needing to convert it for comparison. – pilchard Jan 03 '22 at 01:22
  • If an answer is correct, then the programs breaks after it, and no more questions are asked. I put all of the code here in a for loop 5 times, for 5 questions to be asked. If an answer is incorrect, it works perfectly, but after every correct answer no more questions are asked. May you please suggest how to fix this issue? – Aykhan Jan 05 '22 at 00:31
  • Please open a new question. – Emiel Zuurbier Jan 05 '22 at 08:00