JavaScript Grading Scale Calculating error with multiple wrong answers? - javascript

I'm new to code so my mistake is probably obvious but,
When I go and test the calculator, it reads "A" then where ever the proper grade should be then Undefined. Idk where I'm going wrong.
I've tried a lot of different variations, and can't get the calculator to work properly. I'm not sure where the problem is.
function calculateGrade(grade) {if (parseInt >= "90"){
alert ("A");
}
else if (parseInt >= "80" === parseInt < "90"){
alert ("B");
}
else (parseInt >= "70" === parseInt < "80");{
alert ("C");
}
if (parseInt >= "60" === parseInt < "70"){
alert ("D");
}
else if (parseInt < "60"){
alert ("F");
}}
var inputGrade = prompt("Enter a grade:");
var parsedInt = parseInt(inputGrade);
var finalGrade = calculateGrade(parsedInt);
alert(finalGrade);

Suggestions and errors in your code
You already have parsed into number, so leave the '90' quotes from the numbers.
Don't use magic names and global variables. Your function accepts the grade argument. Use it in your code.
Your if else conditions are wrong. Some of them are without else if. You can left the second part of each else if conditions.
Return the final which you expect from the function.
function calculateGrade(grade) {
let final = '';
if (grade >= 90) {
final = 'A';
} else if (grade >= 80) {
final = 'B';
} else if (grade >= 70) {
final = 'C';
} else if (grade >= 60) {
final = 'D';
} else {
final = 'F';
}
return final;
}
let inputGrade = prompt("Enter a grade:");
let parsedInt = Number.parseInt(inputGrade);
let finalGrade = calculateGrade(parsedInt);
alert(finalGrade);

You could use a patttern with early exit and start frim the smallest value check to the greatest value.
The early exit returns a function and no more check is performed, because the function has ended with return statement.
For taking an integer value with parseInt, you should use a radix of 10, because without and with leading zero the number is treated as octal number, which you do not want.
A last advice, please do not use name of build in functions or objects or reserved words as variable names. This could lead to not proper working code and to searching without reason.
function calculateGrade(grade) {
if (grade < 50){
return "F";
}
if (grade < 60){
return "E";
}
if (grade < 70) {
return "D";
}
if (grade < 80) {
return "C";
}
if (grade < 90) {
return "B";
}
return "A";
}
var inputGrade = prompt("Enter a grade:"),
grade = parseInt(inputGrade, 10),
finalGrade = calculateGrade(grade);
console.log(finalGrade);

Try it
function calculateGrade(grade) {
if (grade < 60){
alert ("F");
}
else if (grade >= 60 && grade < 70){
alert ("D");
}
else if(grade >= 70 && grade < 80);{
alert ("C");
}
else if (grade >= 80 && grade < 90){
alert ("B");
}
else if (grade >= 90){
alert ("A");
}
}
var inputGrade = prompt("Enter a grade:");
var parsedInt = parseInt(inputGrade);
var finalGrade = calculateGrade(parsedInt);
alert(finalGrade);

Related

terminate a prompt dialogue box when user enters "-1" [javascript]

I am having some troubles with js code. I need to prompt the user to enter a valid number (between 0 and 120). If the entry is invalid, it should just display the starting prompt. However, if the user enters "-1", it should terminate the dialogue box.
My dialogue box does not terminate when I enter "-1". What could be the issue? Here is my code
let numGrade; //variable that holds number grade entry
let letter; //this variable holds grade as a letter
//this function checks whether our grade within the range
numGrade = window.prompt("Enter number grades from 0 to 120\nOr enter - 1 to end entries")
if (numGrade == -1){
return false;
}
else if(numGrade<=120 && numGrade>=0){
//calling replaceGrades function, passing a number grade to convert it to a letter grade
// store a grade letter in "final"
final = replaceGrades(numGrade)
//display a number grade and letter grade
alert("Number grade = " + numGrade + "\nLetter grade = " + final)
//this function takes in number grade as a parameter--
// and return a letter grade
function replaceGrades(grade) {
let letterGrade; //variable that returns a letter grade
//if else-if to convert number grades to letter grades{
if (grade >= 100 && grade <= 120) {
return letterGrade = "A";
} else if (grade >= 80 && grade <= 99) {
return letterGrade = "B";
} else if (grade >= 70 && grade <= 79) {
return letterGrade = "C";
} else if (grade >= 60 && grade <= 69) {
return letterGrade = "D"
} else {
return letterGrade = "F";
}
}
}
else {
numGrade = window.prompt("Enter number grades from 0 to 120\nOr enter - 1 to end entries")
}

How to write a while loop inside an if-else loop

Please tell me what is wrong with my code. It seems like after continue; it still loops over the same block even if I use the largest number as an input. Here it still wants me to input a larger number:
// 1) Generate a random integer from 0 to 10 (reference: Math.random())
const RanNum = Math.floor(Math.random() * Math.floor(11))
console.log(RanNum)
// 2) Ask the user input (reference: prompt())
let userInput = prompt(`Give me a number`)
const userInputInt = parseInt(userInput)
console.log(userInput)
console.log(typeof(userInput))
console.log(userInputInt)
console.log(typeof(userInputInt))
if(isNaN(userInput)){
prompt(`Give me a freaking number`)
}else{
let x = 0;
while (x < 4) {
console.log('hi')
console.log(userInputInt)
console.log(RanNum)
if (userInputInt == RanNum) {
console.log(`win`)
prompt('YOU GOT IT MAN')
break;
}
else if (userInputInt < RanNum) {
x = x+1 ;
prompt('Larger please')
continue;
}
else if (userInputInt > RanNum) {
x= x+1
prompt('Smaller please')
continue;
}
}
if(x > 3){alert('More than 3 times')}
}
However, this one works fine. Can someone point to me what's wrong?
// Guess the number
const randomNumber = Math.floor(Math.random() * 11);
let trials = 0;
while(trials < 4){
const guess= parseInt(prompt("Give me a number(0-10)!"));
if(isNaN(guess)){
alert("You are not inputing a number");
// Works for while-loop, for-loop, do-while loop
continue;
}
trials++;
if(guess === randomNumber){
// Equal
alert("You win!!");
// If the player wins, terminate the game
// Works for while-loop, for-loop, do-while loop
break;
}else{
// Unequal
if(guess > randomNumber){
alert("Too large!");
}else{
alert("Too small");
}
}
}
if(trials > 3){
alert("You loses");
}
You can use switch-case except if-else:
let i = 0,
solution = Math.floor(Math.random() * Math.floor(11)),
max_tries = 3;
while (nmb !== solution && i < max_tries + 1) {
if (i < max_tries) {
var nmb = Number(prompt("Put number (1 - 10): "));
switch(true) {
case nmb > solution : console.log("Smaller please"); break;
case nmb < solution : console.log("Largest please"); break;
default : console.log("YOU GOT IT MAN");
}
}
else { console.log("You lose! Number was: " + solution) }
i++
}
You only need to add outputs to the console as in your variant.

How to check if a character is a letter or a number in javascript?

I am new to javascript I'm trying to check user entered the alphabet or a number.
if the user enters "A" it shows Alphabet it's ok but if the user enters "1" I want to show Number but its show alphabet.
where i done wrong.
Thanks Advance
function CHECKCHARATCTER(Letter) {
if (Letter.length <= 1) {
if ((64 < Letter.charCodeAt(0) < 91) || (96 < Letter.charCodeAt(0) < 123)) {
return "Alphabhate";
}
else if (47 < Letter.charCodeAt(0) < 58) {
return "NUMBER";
}
else { return "Its NOt a NUMBER or Alphabets"; }
}
else { return ("Please enter the single character"); }
}
a = prompt("enter the number or Alphabhate");
alert(typeof (a));
b = CHECKCHARATCTER(a);
alert(b);
Here:
if (64 < Letter.charCodeAt(0) < 91) //...
JS isn't Python. You can't simply do a < b < c, you need to explicitly use the logical && operator: (a < b) && (b < c).
You can use regular expressions. Please have a look at regular expressions. It will be very helpful.
function checkAlphaNum(char) {
let alphaReg = new RegExp(/^[a-z]/i);
let numReg = new RegExp(/^[0-9]/);
if(alphaReg.test(char)) {
return "ALPHABET";
} else if(numReg.test(char)) {
return "NUMBER";
} else {
return "OTHER";
}
}
console.log("Output : ", checkAlphaNum('A'));
console.log("Output : ", checkAlphaNum(1));
I modified you conditions as it's shown in the following code. Also you can check it out here
function CHECKCHARATCTER(Letter){
if (Letter.length <= 1)
{
if (Letter.toUpperCase() != Letter.toLowerCase()) {
return "Alphabet";
}
else if (!isNaN( Letter)) {
return "Number";
} else{
return "Its Not a Number or Alphabet";
}
}
else {
return("Please enter the single character");
}
}
input = prompt("enter the Number or Alphabet");
output = CHECKCHARATCTER(input);
alert(output);

number to grade letter

As a recent assignment for my coding bootcamp, we've been asked to create a function that takes an array of numbers as an argument and outputs them to an array of letter grades. I am stuck!
I've tried re-working and refactoring my code, changing the placement of different parts of the program, looking through MDN...
let grades = []
function getLetterGrades(grades) {
let grade = grades.map
if (grade < 60) {
return "F";
} else if (grade < 70) {
return "D";
} else if (grade < 80) {
return "C";
} else if (grade < 90) {
return "B";
} else if (grade < 100) {
return "A";
}
console.log(grades);
}
getLetterGrades([95, 85, 71]);
The results will only output the numbers I've entered into the function call.
You are using .map() wrong. What you are doing is comparing the map method to a number. You are not executing anything.
function getLetterGrades(grades) {
return grades.map(function(grade) {
if (grade < 60) {
return "F";
} else if (grade < 70) {
return "D";
} else if (grade < 80) {
return "C";
} else if (grade < 90) {
return "B";
} else if (grade < 100) {
return "A";
}
});
}
var letters = getLetterGrades([95, 85, 71]);
console.log(letters)
Your main issue is this:
let grade = grades.map
You are not invoking the .map method with (), so instead grade is winding up holding a reference to the native map function. And, that function isn't a number, so none of your conditions become true, so you continue past the if statement and just log the array that you passed in.
Instead, you must invoke .map() and supply its required parameter (a function that will be called for each item in the source array). Your if statement should be the body of that function:
let grades = []
function getLetterGrades(grades) {
let letterGrades = grades.map(function(grade){
if (grade < 60) {
return "F";
} else if (grade < 70) {
return "D";
} else if (grade < 80) {
return "C";
} else if (grade < 90) {
return "B";
} else if (grade < 100) {
return "A";
}
});
console.log(letterGrades);
}
getLetterGrades([95, 85, 71]);
Look at this solution:
let grades = []
function getLetterGrades(grades) {
// add an array (grade) that will hold the output
let grade = []
// iterate over grades with forEach()
grades.forEach(item => {
// item will be equal 95 on the first iteration
// 85 on the second, and 71 on the third - these
// values come from the passed 'grades' parameter
if (item < 60) {
grade.push("F");
} else if (item < 70) {
grade.push("D");
} else if (item < 80) {
grade.push("C");
} else if (item < 90) {
grade.push("B");
} else if (item < 100) {
grade.push("A");
}
})
// console.log(grade) - NOT grades!
console.log(grade);
}
getLetterGrades([95, 85, 71]);
The problem was not with the method you chose - the problem was you didn't finish your function. Here's another solution with map():
let grades = []
function getLetterGrades(grades) {
let grade = grades.map(item => {
if (item < 60) {
return "F";
} else if (item < 70) {
return "D";
} else if (item < 80) {
return "C";
} else if (item < 90) {
return "B";
} else if (item < 100) {
return "A";
}
})
// console.log(grade) - NOT grades!
console.log(grade);
}
getLetterGrades([95, 85, 71]);
In this case the main difference between forEach() and map() is that map() returns a NEW array (that's why you return values in the function body), and forEach() doesn't (we had to create the array - grade- manually, and push values into this "hand-made" array).
Look below to see what would happen, if we used forEach() WITHOUT a manually created array:
// THIS IS NOT A GOOD SOLUTION!
// IT GIVES YOU THE ANSWER IN THIS SMALL EXAMPLE
// (so you see that it's possible)
// BUT IN ANY LARGER CODE THIS IS THE
// 100% SURE SOURCE OF ERRORS.
let grades = []
function getLetterGrades(grades) {
grades.forEach((item, index) => {
if (item < 60) {
grades[index] = "F";
} else if (item < 70) {
grades[index] = "D";
} else if (item < 80) {
grades[index] = "C";
} else if (item < 90) {
grades[index] = "B";
} else if (item < 100) {
grades[index] = "A";
}
})
// console.log(grades) - NOT grade!
console.log(grades);
}
getLetterGrades([95, 85, 71]);
(I used the second argument of forEach() - that's index) THIS IS NOT A GOOD SOLUTION! Why? We "destroyed" our original grades array by overwriting it in getLetterGrades() - DON'T DO THIS!
As stated on map() takes a function and runs it once on each object in the array. To be clear on how you're trying to use it:
function getLetterGrades(grade) {
if (grade < 60) {
return "F";
} else if (grade < 70) {
return "D";
} else if (grade < 80) {
return "C";
} else if (grade < 90) {
return "B";
} else if (grade < 100) {
return "A";
}
}
x = [95, 85, 71];
//=> [A, B, C]
x.map(getLetterGrades);
Functionally, this is what the other answers are doing, they just aren't naming the method.
Post edited to change link as comment pointed out better resource.

Wierd execution of if condition

Else condition is executed every time. If input is '11' answer is 'f' not 'D', I know the last condition should be else if but according to the logic of input is 11 output should be 'D'
function getGrade(score) {
let grade;
var score1 = Number(score);
// Write your code here
if (score1 > 25 && score <= 30)
grade = "A";
else if (score1 > 20 && score <= 25)
grade = "B";
else if (score1 > 15 && score <= 20)
grade = "C";
else if (score1 > 10 && score <= 15)
grade = "D";
else if (score1 > 5 && score <= 10)
grade = "E";
else (score1 > 0 && score <= 5)
grade = "F";
return grade;
}
Is it a copy-paste? Then it's a matter of typo.
else (score1 > 0 && score <= 5)
grade = "F";
if is missing here. Therefore, (score1 > 0 && score <= 5) is interpreted as the thing to do (so, evaluate an expression), and the next line is outside of any else/if branch and simply gets executed always.
You can use the parenthesis around the else if. Also for the last condition you can simple use else instead of else if
function getGrade(score) {
let grade;
var score1 = Number(score);
console.log(score1)
// Write your code here
if (score1 > 25 && score <= 30) {
grade = "A";
} else if (score1 > 20 && score <= 25) {
grade = "B";
} else if (score1 > 15 && score <= 20) {
grade = "C";
} else if (score1 > 10 && score <= 15) {
grade = "D";
} else if (score1 > 5 && score <= 10) {
grade = "E";
} else {
grade = "F";
}
return grade;
}
console.log(getGrade(11))
A better approach, is to use an early exit paradigm, starting with wrong values and then take a ladder of conditions which rely on the conditions before.
function getGrade(score) {
var score1 = Number(score);
if (isNaN(score1) || score1 > 30 || score1 < 0) return;
if (score1 > 25) return "A";
if (score1 > 20) return "B";
if (score1 > 15) return "C";
if (score1 > 10) return "D";
if (score1 > 5) return "E";
return "F";
}

Categories