Calculating and displaying the result depending on the score - javascript

In the following JavaScript code you answer both questions and then you will get a specific answer based on your score.
Let's say, you choose Yes a lot for the first question and Chocolate for the second question, you will score 8 points and instead of displaying the number 8 I would like to display a comment. That's why I have created an if loop, but for some reason the javascript code is displaying nothing, any suggestions for a solutions?
By the way you can find the code in the following link:
http://jsfiddle.net/9N5ZV/
if (totalScore <=2) {
calculate = healthy;
} else if (totalScore >= 3 && totalScore <= 6) {
calculate = average;
} else {
calculate = unhealthy;
}

Your condition syntax is wrong, and you use variables out of scope.
Demo
function getTotal()
{
var totalScore = getScoreCake() + getScoreChoco();
document.getElementById('result').innerHTML =
//"Your total score is: "+totalScore;
getComment(totalScore);
}
function getComment(score)
{
if (score <=2)
return healthy;
else if(score >= 3 && score <=6)
return average;
else
return unhealthy;
}

You need an else if
if (totalScore <=2) {
calculate = healthy;
} else if (totalScore >= 3 && totalScore <= 6) {
calculate = average;
} else {
calculate = unhealthy;
}
Also, use the console! You'll see:
Uncaught SyntaxError: Unexpected number
This was due to the else (expr) clause, it's else if

You conditional statement has errors. Should be:
if (totalScore <= 2) {
calculate = healthy;
} else if (totalScore >= 3 && totalScore <= 6) {
calculate = average;
} else {
calculate = unhealthy;
}
Here is an updated jsFiddle.
EDIT:
You are not calling getComment function. Try the one below to see how you can output the string.
http://jsfiddle.net/9N5ZV/5/

Related

functions result is NaN

I am really new in coding therefore I am coding currently a Taximeter. Unfortunately is the result of my code when executing NaN in the console. I tried some ways to rectify my problem but those attempts did not work. I think that some variables are not in the right scope but I do not know how to fix that.
function Taximeter() {
const y = 3.9;
const km = prompt("How far is your target");
if (km <= 7) {
var routePrice = 2.3;
} else if (km > 7) {
let routePrice = 1.65;
var subtractedLength = (km -= 7);
var partialExpenses = (subtractedLength *= routePrice);
var tosevenExpenses = 7 * 2.3;
var combinedExpenses = (tosevenExpenses += partialExpenses);
}
const persons = prompt("How much persons are driving with you?");
if (persons > 8) {
console.log("Only 8 persons can drive with you.");
} else if (8 >= persons >= 5) {
var personsExpenses = 5;
} else if (0 >= persons >= 4) {
personExpenses = 0;
}
if (km <= 7) {
var wholeExpenses = y + km * routePrice + personsExpenses;
} else {
var wholeExpenses = combinedExpenses + y + personsExpenses;
}
console.log(wholeExpenses);
}
It would be helpful to know where exactly NaN is coming up and whether or not you are seeing NaN as the result of an Exception (if an error message was logged to the console) or if NaN is coming up as a result of your own console.log() statements. Part of the issue could be that the function prompt() returns a String, meaning that your variable km is going to be a String and not a Number. Use this line of code instead and it might fix your problem:
const km = parseInt(prompt("How far is your target"));
EDIT:
In response to your comment, there are a couple other issues I see here. There is the issue with your first if and else if clauses where the indentation is a little off. This, as far as I can tell, should not actually affect your code, but it does make it harder to read. Here is how it should look:
if (km <= 7) {
var routePrice = 2.3;
} else if (km > 7) {
let routePrice = 1.65
var subtractedLength = km -= 7;
var partialExpenses = subtractedLength *= routePrice ;
var tosevenExpenses = 7 *2.3;
var combinedExpenses = tosevenExpenses += partialExpenses;
};
Second, in those same if and else if clauses, you use the -=, *=, and += operators when they are unnecessary and may cause errors. I've never seen them used the way that you have before, so I don't know if they actually cause errors, but I would edit those clauses one more time for readability at least:
if (km <= 7) {
var routePrice = 2.3;
} else if (km > 7) {
let routePrice = 1.65
var subtractedLength = km - 7;
var partialExpenses = subtractedLength * routePrice ;
var tosevenExpenses = 7 *2.3;
var combinedExpenses = tosevenExpenses + partialExpenses;
};
Like with km I would also edit your persons declaration to turn that variable into a Number so that the logic operators that you use on it later work properly:
const persons = parseInt(prompt("How much persons are driving with you?"));
Another thing, like a commenter earlier pointed out, 8 >= persons >= 5 will not work the way you think it will - just edit those if and else if clauses like so to fix that error:
if (persons > 8) {
console.log("Only 8 persons can drive with you.");
} else if(persons >= 5 && persons <= 8) {
var personsExpenses = 5;
} else if (persons <= 4 && persons >= 0) {
personExpenses = 0;
};
Finally, your variable declaration of personsExpenses is such that the variable will only be declared if that first else if clause resolves. You need personsExpenses to be declared no matter what, so I would declare it before and outside of any of those conditional clauses:
var personsExpenses
if (persons > 8) {
console.log("Only 8 persons can drive with you.");
} else if(persons >= 5 && persons <= 8) {
personsExpenses = 5;
} else if (persons <= 4 && persons >= 0) {
personExpenses = 0;
};
That's everything that I noticed, so good luck!

making a point counter for a dice game in javascript

I am trying to make a dice game point counter where you are awarded points based on how close your guess of what you thought the number was going to be to what the number rolled is. My current code looks like this
function continueL(e){
if (e.keyCode == Keyboard.letter('L')){
add(copter);
var evorod = readInt("What number do you think it's going to be? You are guessing ");
println("Please click the die to roll a number");
mouseClickMethod(contin);
}
}
function contin(e){
var num = Randomizer.nextInt(1,12);
println("The number rolled is.... " + num);
var numText = new Text("The number rolled is...." + num, "20pt Arial");
numText.setPosition(50, 200);
numText.setColor(Color.red);
add(numText);
if (num == evorod){
println("Congrats! You Win! Here is 100 points");
} else {
if(num == evorod - 1 || num == evorod + 1){
println("So close! Here is 80 points!");
} else {
if(num == evorod - 2 || num == evorod + 2){
println("Almost got it. Take 60 points!");
} else {
if(num == evorod - 3 || num == evorod + 3){
println("Nice try. Take 40 points!");
} else {
if(num == evorod - 4 || num == evorod + 4){
println("Whoops... maybe next time? Take 20 points");
} else {
println("Better luck next time.");
}
}
}
}
}
remove(copter);
}
But it only displays the final else no matter what your guess was vs the number rolled.
edit: evorod is a global variable
evorod needs global scope, right now it only exists inside the continueL() function so will be undefined when you try to use it in contin(). Fix that by declaring it outside the function.
Meanwhile your if statements could be simplified to this, instead of a bunch of separate nested conditionals:
if (num == evorod) {
println("Congrats! You Win! Here is 100 points"); // there is no println in javascript, I'll assume you've coded your own equivalent
} else if (num == evorod - 1 || num == evorod + 1) {
println("So close! Here is 80 points!");
} else if (num == evorod - 2 || num == evorod + 2) {
println("Almost got it. Take 60 points!");
} else if (num == evorod - 3 || num == evorod + 3) {
println("Nice try. Take 40 points!");
} else if (num == evorod - 4 || num == evorod + 4) {
println("Whoops... maybe next time? Take 20 points");
} else {
println("Better luck next time.");
}
Try a switch statement instead. There are 6 possible outcomes per throw. If you guessed less or more than the actual outcome you lose 20 points per digit away from the true outcome.
First of all, let's find how off your prediction was from the roll. We do that by subtracting (excuse my shabby math).
int outcome = ...
int guess = ...
int difference;
if(outcome > guess)
difference = outcome - guess;
else if(outcome < guess)
difference = guess - outcome;
switch(difference)
{
case 0:
{
System.out.println("100 Wondred points!");
break;
}
case 1:
{
System.out.println("You get 80 hamsters!");
break;
}
}
And so on it goes, with a difference of 5 being the lowest score because it means you were 5 numbers away from the outcome.

Grading Students in JS with recursion - Range Error

I was trying to work on this hackerrank problem.
Every student receives a grade in the inclusive range from
0-100 to .
Any less than 38 is a failing grade.
Sam is a professor at the university and likes to round each student's according to these rules:
If the difference between grade the and the next multiple of
5 is less than 3, round up to the next multiple of 5. If the value of grade is less than 38, no rounding occurs as the
result will still be a failing grade.
Given the initial value of for each of Sam's students, write code to
automate the rounding process.
My code is:
function gradingStudents(grades) {
const roundup = y => y + 1;
{
if ( grades < 38 || grades % 5 === 0) return grades;
else if ( grades % 5 < 4 && grades % 5 !== 0) return roundup(grades);
}
{
if (roundup % 5 === 0) return roundup;
else { gradingStudents(roundup + 1) }
}
}
gradingStudents(38) // -> 39
I tried to use Math.ceil(grades) inside the variable roundup but output didnt change. So, when you invoke the function with a number that is not before a multiple of 5 (e.g. 43) it returns the proceeding number. However, if it is the number before a multiple of 5 it gives a range error. "maximum call stack size reached."
As far as I got, the code doesnt proceed to the second part. Even if it did, I am not sure if it would fetch the current value of the function roundup when dealing with if statements in the second block.
What do I dont get in here?
Also, this is actually meant for an array output but since I am a beginner I am pretty much okay with this one for the start as well :D .
Javascript solution:
function gradingStudents(grades) {
return grades.map((grade) => {
if (grade > 37) {
const offset = 5 - (grade % 5);
if (offset < 3) {
grade += offset;
}
}
return grade;
});
}
Try this:
function gradingStudents(grades) { //input: 43
var finalGrade;
if(grade < 38)
return grades;
else{
var gradeDif = grades % 5; //3
if(gradeDif > 3){
return grades;
}
else {
return grades + (5 - gradeDif); //Output: 45
}
}
}
One solution calculates the next multiple of 5 no bigger than the grade and uses that value to test whether or not to round up (next5 - grade < 3).
We write a simple function to round an individual grade and then for a list of grades use .map with that function.
const roundGrade = (grade) => {
const next5 = 5 * Math.ceil (grade / 5)
return (grade < 38) ? grade : (next5 - grade < 3) ? next5 : grade
}
const gradingStudents = (grades) =>
grades .map (roundGrade)
console .log (gradingStudents ([73, 67, 38, 33]))
Note that, like most solutions to this problem, no recursion is needed.
1-Use the Array.prototypt.map according to the question logic.
const gradingStudents = (grades) => grades
.map(n => (n >= 38 && n % 5 >= 3)?(n + ( 5 - ( n % 5 ) )):n )
let result = gradingStudents([0,25,38,56,89,77,78,57,58])
console.log(result)
My solution is this
function gradingStudents(grades) {
grades.map((grade,i)=>{
if(grade >= 38){
let fg = (grade/5).toString().split('.');
if(fg[1]>5){
grades[i]=((parseInt(fg[0],10)+1) * 5);
};
}
});
return grades;
}
console.log(gradingStudents([73,67,38,33]));
my solution:
function gradingStudents(grades) {
return grades.map(function(grade) {
return (grade >= 38 && grade % 5 >= 3) ? grade + 5 - (grade % 5) : grade;
});
}

Else if Statement ( the last condition is always picked

if (q1 == "1-25") {
score = 0;
}
else if (q1 == "26-40"){
score = 5;
}
else if (q1 == "41-60"){
score = 8;
}
else (q1 == "60+")
score = 10;
this is a segment of my code from a multi-choice test but no matter what option I pick, the score variable always chooses 10
A possible error in the format of my code?
The problem is this:
} else (q1 == "60+");
score = 10;
Thanks to ASI, (q1 == "60+") is the expression that is run in the else part, score = 10 is always executed after the if/else. Might do:
} else {
score = 10;
}
Or
} else if (q1 == "60+"){
score = 10;
}
And please always use semicolons to seperate statements and curly braces to annotate blocks.
else shouldn't be followed by a condition. Javascript doesn't require curly braces so it's probably executing the condition as a statement (since else doesn't accept a condition) and then the final score is a separate statement outside of the if-else logic.
If I add braces to your current code, you can see where the problem lies:
if (q1 == "1-25") {
score = 0;
}
else if (q1 == "26-40"){
score = 5;
}
else if (q1 == "41-60"){
score = 8;
}
else
{
(q1 == "60+");
}
score = 10;
So you can see that, because you're using else rather than else if, the "condition" is executed by the else, evaluated to true/false and then thrown away. And then, after the if statement is done, score is set to 10.
Here is problem
else (q1 == "60+")
score = 10;
You are missing if
Or remove this condition.
Else cannot have condition

Can't detect why my loop is infinite

var randomNum = Math.round(Math.random() * 100);
guesses = prompt("guess a number between 1 and 100");
var scores = 0;
while (randomNum < 100) {
if (guesses < randomNum) {
console.log(" too low.. continue")
} else if (guesses > randomNum) {
console.log("too high ... continue ");
score++;
} else if (guesses === randomNum) {
console.log("great ... that is correct!!")
} else {
console.log("game over ... your guess was right " + scores + " times");
}
}
I have been struggling with the while loop concept for some time now and in order to confront my fears I decided to practice with some tiny exercises like the one above.
You're not incrementing randomNum hence it will always stay in an infinite loop.
You initialize randonNum and guesses at the beginning of your code, but then you never change their values again. So, once you go inside the while loop and the condition starts out to be false, then there is nothing inside the while loop to ever change the outcome of the comparison condition. Thus, the condition is always false and you end up with an infinite loop. Your loop structure boils down to this:
while (randomNum < 100) {
// randomNum never changes
// there is no code to ever break or return out of the loop
// so loop is infinite and goes on forever
}
You can fix the problem by either putting a condition in the loop that will break out of the loop with a break or return or you can modify the value of randomNum in the loop such that eventually the loop will terminate on its own.
In addition, guesses === randomNum will never be true because guesses is a string and randomNum is a number so you have to fix that comparison too.
It's not 100% clear what you want to achieve, but if you're trying to have the user repeatedly guess the number until they get it right, then you need to put a prompt() inside the while loop and a break out of the while loop when they get it right or ask to cancel:
var randomNum = Math.round(Math.random() * 100);
var guess;
var score = 0;
while ((guess = prompt("guess a number between 1 and 100")) !== null) {
// convert typed string into a number
guess = +guess;
if (guess < randomNum) {
console.log(" too low.. continue")
} else if (guess > randomNum) {
console.log("too high ... continue ");
score++;
} else if (guess === randomNum) {
console.log("great ... that is correct!!")
console.log("score was: " + score);
// when we match, stop the while loop
break;
}
}
the below line of code of your assign randomNum only one time hence it doesn't change
var randomNum = Math.round(Math.random() * 100);
so when you are trying to create the while loop the randomNum value remains same
try changing the randomNum value in the while loop
I think this is what you tried to achieve. Retry x number of times
var randomNum = Math.round(Math.random() * 100);
var guesses;
var scores = 0;
var tries = 0
while (tries++ < 3) { // Loop if less than 3 tries, and increment
guesses = prompt("guess a number between 1 and 100");
if (guesses < randomNum) {
console.log(" too low.. continue")
} else if (guesses > randomNum) {
console.log("too high ... continue ");
} else {
// It's not to low, not to high. It must be correct
score++;
console.log("great ... that is correct!!");
randomNum = Math.round(Math.random() * 100);
}
}
console.log("game over ... your guess was right " + scores + " times");

Categories

Resources