Scrappy Coco
Scrappy Coco

Reputation: 3

The code stores and prints only second value?

Here is the code that stores only the second value. I understand that it stores the last value, but where is my first value? Was my first value overwritten?

let input;
let answer;

quest = ['True or false: 5000 meters = 5 kilometers?',"Is your name Chang?"];
ans = ["True", "False"];

function print(input, quest){
   for(let i = 0; i < 2; i++){
     input = require('readline-sync');
     answer = input.question(quest[i] + " ");
   }
}

function ansCorr(answer){
  for(let i = 0; i < 2; i++){
    console.log("\n" + quest[i]);
    console.log("Your answer: " + answer);
    console.log("Correct answer : " + ans[i]);
    if(answer === ans[i]){
    score++;
    }
  }
}

print(input, quest);
ansCorr(answer);

Here is the output:

True or false: 5000 meters = 5 kilometers? True
Is your name Chang? False

True or false: 5000 meters = 5 kilometers?
Your answer: False
Correct answer : True

Is your name Chang?
Your answer: False
Correct answer : False

Instead of True it prints False for the first question. How to fix it?

Upvotes: 0

Views: 49

Answers (1)

ZaO Lover
ZaO Lover

Reputation: 433

You should use an array for ans variable. Here's the code.

let answer = [];
let score = 0;

quest = ['True or false: 5000 meters = 5 kilometers?',"Is your name Chang?"];
ans = ["True", "False"];

function print(input, quest){
   for(let i = 0; i < 2; i++){
     input = require('readline-sync');
     answer.push(input.question(quest[i] + " "));
   }
}

function ansCorr(answer){
  for(let i = 0; i < 2; i++){
    console.log("\n" + quest[i]);
    console.log("Your answer: " + answer[i]);
    console.log("Correct answer : " + ans[i]);
    if(answer === ans[i]){
    score++;
    }
  }
}

print(input, quest);
ansCorr(answer);

Upvotes: 1

Related Questions