0

Im a complete beginner in programming and I need some help. Im doing an exercise where we have 3 players. Each one must input a height and an age. The winner is then decided based on total score of height + 5 * age. My program works but my calculations are wrong (and higher). So for example. Lets say that heightJohn = 10 and ageJohn = 1. That should mean that totalJohn is 15 right? If I assign 10 and 1 without the prompt the totalJohn really is 15. But when I use prompt, somehow my console displays that totalJohn = 105. I really dont understand how and why? Can someone enlighten me, I cant figure out what Im doing wrong.

let heightJohn = prompt("What is Johns height?");
let ageJohn = prompt("What is Johns age?");
let heightBob = prompt("What is Bobs height?");
let ageBob = prompt("What is Bobs age?");
let heightMichael = prompt("What is Michaels height?");
let ageMichael = prompt("What is Michaels age?");
let totalJohn = (heightJohn + 5 * ageJohn);
let totalBob = heightBob + 5 * ageBob;
let totalMichael = heightMichael + 5 * ageMichael;


console.log(ageJohn);
console.log(heightJohn);
console.log(totalJohn);
console.log(totalBob);
console.log(totalMichael);

if(totalJohn > totalBob && totalJohn > totalMichael) {
    console.log("John is a winner with the score of " + totalJohn)
} else if(totalBob > totalJohn && totalBob > totalMichael) {
    console.log("Bob is a winner with the score of " + totalBob)
} else if(totalMichael > totalJohn && totalMichael > totalBob) {
    console.log("Michael is a winner with the score of " + totalMichael)
} else if(totalJohn === totalBob === totalMichael) {
    console.log("Its a draw with the score of " + totalMichael)
} else {
    console.log("Wrong input");
}
Urrby
  • 41
  • 5
  • All of the variables you get from prompts are strings. When you add a string and a number you are concatenating two strings. So, [convert the string to a number](https://stackoverflow.com/questions/1133770/how-do-i-convert-a-string-into-an-integer-in-javascript) before adding it. – James Jan 06 '18 at 19:34
  • the prompt is returning a string, so 10 + "5" = "105". You can convert the prompt results from a string to a number by setting heightJohn = parseInt(prompt("What is John's age?"), 10). This will convert the prompt result from a string to a number. – programming for fun Jan 06 '18 at 19:36
  • Thank you so much. I would ask you for just one more clarification. Why doesnt let totalJohn = parseInt(heightJohn + 5 * ageJohn); work? Shouldnt that also convert everything to Integer? – Urrby Jan 06 '18 at 19:41
  • `parseInt` only converts a string which contains an *integer*, not any arbitrary expressions with +,-,* embedded in them. You need to parseInt heightJohn and ageJohn separately, e.g. `parseInt(heightJohn) + 5 * parseInt(ageJohn)` – President James K. Polk Jan 06 '18 at 20:48

0 Answers0