terminate a prompt dialogue box when user enters "-1" [javascript] - 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")
}

Related

Javascript not rounding properly

I made a simple number guessing game in javascript which goes from 1 to 100.
My problem is that everything works, except when I type a decimal number from 100 to 101. I want my code to give me the "Please enter a number from 1 to 100" message then, but it doesn't.
How do I get Javascript to round this properly?
let randomNumber = Math.floor(Math.random() * 100); // Random number
function guess() {
let inp = document.getElementById("number").value; // Reading input
let inpRounded = Math.floor(inp);
// Random number is higher
if (inpRounded < randomNumber && inpRounded >= 1 && inpRounded <= 100) {
document.getElementById("result").innerHTML = "Higher";
}
// Random number is lower
else if (inpRounded > randomNumber && inpRounded >= 1 && inpRounded <= 100) {
document.getElementById("result").innerHTML = "Lower";
// Input matches random number
} else if (inpRounded == randomNumber && inpRounded >= 1 && inpRounded <= 100) {
document.getElementById("result").innerHTML = "You won!";
}
// Input is weird
else if (inpRounded == null) {
document.getElementById("result").innerHTML = "Please enter a valid number";
}
// Input is lower than 1 or higher than 100
else if (inpRounded < 1 || inpRounded > 100) {
document.getElementById("result").innerHTML = "Please enter a number from 1 to 100";
}
// Other issue
else {
document.getElementById("result").innerHTML = "Error"
}
}
<h2>Enter a number from 1 to 100</h2>
<input type="number" placeholder="Type your guess here" id="number">
<input type="button" value="Go!" onclick="guess()">
<p id="result"></p>
Don't round the number initially, otherwise you'll lose the decimal information you need when you want to reject values between 100 and 101.
function guess() {
const value = document.getElementById("number").value; // Reading input
const numValue = Number(value);
if (numValue < 1 || numValue > 100) {
document.getElementById("result").textContent = "Please enter a number from 1 to 100";
return;
}
const inpRounded = Math.floor(numValue);
// etc
Just put this code first before you check other things.
if (inpRounded == null) {
document.getElementById("result").innerHTML = "Please enter a valid number";
return;
}
if (inpRounded < 1 || inpRounded > 100) {
document.getElementById("result").innerHTML = "Please enter a number from 1 to 100";
return;
}

trying to turn my working code into a function

I am trying to turn this working code I have into a function for a course I am taking.
<!DOCTYPE html>
<html>
<body>
<script>
var entry;
var letterGrade;
var total = 0; // you forgot to set the start value for total
var entryCount = 0; // also for entry count you must initialize first.
// add the error string here so we dont have to duplicate it in the code.
var errorString = "Entry must by a valid number from 0 through 100\nOr enter 999 to
end entries";
do {
// get something from user
entry = prompt("Enter number grade from 0 through 100\nOr enter 999 to end entries",
999);
// the user may also enter something that is not a number
if(isNaN(entry)){ // check if it is not a number
alert(errorString); //show error if not a number
}else{
// you now know you have a number so you can parse it
entry = parseInt(entry); // convert to number
// now check for a valid number
if (entry >= 0 && entry <= 100) {
// number is in valid range check each grade
if (entry < 50) {
letterGrade = "F";
}else
if (entry < 70) {
letterGrade = "D";
}else
if (entry < 80) {
letterGrade = "C";
}else
if (entry < 90) {
letterGrade = "B";
}else
if (entry <= 100) {
letterGrade = "A";
}
total += entry; // add the total
entryCount += 1; // add ont to count
// display entry and grade
alert("Number grade = " + entry + "\nLetter grade = " + letterGrade);
}else // if not in valid range check if its 999
if (entry != 999) {
alert(errorString); // no show error
}
}
}while (entry != 999); // do this till 999 is entered
</script>
</body>
</html>
The code itself is doing what it is supposed to do but according to the assignment I have to call a function like
function myFunction(){}
I am not crazy about hitting 999 to break the prompt either if anyone has any suggestions bout that as well it would be greatly appreciated
Here I am calling function normally. You can add this function to be called on a certain event like page load or button click.
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
var entry;
var letterGrade;
var total = 0; // you forgot to set the start value for total
var entryCount = 0; // also for entry count you must initialize first.
// add the error string here so we dont have to duplicate it in the code.
var errorString = "Entry must by a valid number from 0 through 100\nOr enter 999 to end entries";
do {
// get something from user
entry = prompt("Enter number grade from 0 through 100\nOr enter 999 to end entries",
999);
// the user may also enter something that is not a number
if (isNaN(entry)) { // check if it is not a number
alert(errorString); //show error if not a number
} else {
// you now know you have a number so you can parse it
entry = parseInt(entry); // convert to number
// now check for a valid number
if (entry >= 0 && entry <= 100) {
// number is in valid range check each grade
if (entry < 50) {
letterGrade = "F";
} else
if (entry < 70) {
letterGrade = "D";
} else
if (entry < 80) {
letterGrade = "C";
} else
if (entry < 90) {
letterGrade = "B";
} else
if (entry <= 100) {
letterGrade = "A";
}
total += entry; // add the total
entryCount += 1; // add ont to count
// display entry and grade
alert("Number grade = " + entry + "\nLetter grade = " + letterGrade);
} else // if not in valid range check if its 999
if (entry != 999) {
alert(errorString); // no show error
}
}
} while (entry != 999); // do this till 999 is entered
}
myFunction();
</script>
</body>
</html>

JavaScript Grading Scale Calculating error with multiple wrong answers?

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);

Score to Grade converter, or: Why is my switch statement buggy? (Javascript)

I'm working on switch statements at the moment, and have a little function below that turn a given numerical score into a grade. Or at least that's what it's supposed to do, but somehow it all goes wrong, and I'm not sure why!
function convertScoreToGrade(score) {
var grade = "";
switch(score) {
case 100>=score && score>=90: grade = "A";
break;
case 89>=score && score>=80: grade = "B";
break;
case 79>=score && score>=70: grade = "C";
break;
case 69>=score && score>=60: grade = "D";
break;
case 59>=score && score>=0: grade = "F";
break;
case score>100 || score<0: grade = "INVALID SCORE";
} return grade;
}
convertScoreToGrade(10);
For example, when I input the number 10 I only get an empty string, which suggests that the relevant case isn't evaluated. Any help would be appreciated.
Based on your example, here is a modification to make your code work
The big take away here is you match the parameter you pass into the switch statement. So passing a boolean value of true means that if your condition is true, that will be the case.
IMO, a switch statement is what you should use for this case. It's a small amount of cases (5), and is very readable for anyone who will work on or maintain this code at a later point.
function convertScoreToGrade(score) {
// Check for invalid scores first
if(typeof score !== 'number' || score < 0 || score > 100)
return "INVALID SCORE";
var grade = "";
// Pass a boolean value, remember we are matching this value
// EX: (score < 90) is true when score is 0 - 89
switch(true) {
case score < 60:
grade = "F";
break;
case score < 70:
grade = "D";
break;
case score < 80:
grade = "C";
break;
case score < 90:
grade = "B";
break;
case score <= 100:
grade = "A";
break;
}
// If you want partial grades
if(score % 10 <= 3 && score !== 100 )
grade += "-";
else if(score % 10 >= 7 || score == 100)
grade += "+";
return grade;
}
// These are small test cases to show you
// that convertScoreToGrade works as defined
console.log(convertScoreToGrade(-1));
console.log(convertScoreToGrade(101));
console.log(convertScoreToGrade('The dog ate it.'));
var i = 50;
while(i <= 100){
console.log(i, 'should be', convertScoreToGrade(i));
i += 4;
}
Bad solution that you might think of that is clearly worse than the alternative but I already typed it and I think it's helpful for you to understand that this is how you'd handle it with if statements. Please have mercy on me for posting such lousy code.
function convertScoreToGrade(score) {
var grade = "";
if(score>=0){
grade = "F";
}
if(score>=60){
grade = "D";
}
if(score>=70){
grade = "C";
}
if(score>=80){
grade = "B";
}
if(score>=90){
grade = "A";
}
if (score>100 || score<0){
grade = "INVALID SCORE";
}
return grade;
}
convertScoreToGrade(10);
function convertScoreToGrade(score) {
// scores is an array of objects
// Each element in the scores array has two properties, grade and score
// grade is the letter grade, score is the minimum score to achieve that grade
var i,l,scores = [{ grade: 'A', score: 90},
{grade: 'B',score : 80},
{grade: 'C',score: 70},
{grade: 'D',score: 60 }];
// Ensure score is between 0 and 100 inclusive
if (score < 0 || score > 100) {
return 'Invalid';
}
// Loop through all the scores and exit when the score is larger than the minimum
l = scores.length;
for (i=0;i<l;i++) {
if (score >= scores[i].score) {
return scores[i].grade;
}
}
// If the score was not found, the grade is an F
return 'F';
}
console.log(convertScoreToGrade(82));
console.log(convertScoreToGrade(90));
console.log(convertScoreToGrade(50));

JavaScript how to ensure user enters a number between 1 and 100

Hello i want the user to enter a number between 1 and 100 any higher i want it to display array out of bounds and not add the number to the array here is what i have and it works but when u enter in another number it says NAN
for(var i = 0; Repeat !== 'n'; i++){
Student.push(prompt("Enter Student Name: "));
Mark.push(parseInt (prompt("Enter Student mark: ")));
//Check if Mark entered is not out of bounds and gives a grade
if (Mark[i] <0 || Mark[i] >100){
alert("Grate out of bounds");
Mark.splice(i);//Removes array if out of bounds
}else if (Mark[i] >= 83){
getGrade.push("A");
A++;
}else if (Mark[i] >= 70){
getGrade.push ("B");
B++;
}else if (Mark[i] >= 50){
getGrade.push ("C");
C++;
}else if (Mark[i] >= 0){
getGrade.push ("F");
F++;
//If mark is not a number
}else if (isNaN(Mark)){
alert("Must input numbers");
}
Repeat = prompt ("Do you want to enter another student: y/n");
}
When you enter an incorrect value, the array is no longer in sync with i. For example, if you enter (Bob and 1000) for the first grade, consider what gets stored into the variables after the call to Mark.splice(i):
Student = [Bob]
Mark = []
Now Mark is empty, and i has been incremented to 1. Let's say you now enter values Johnny and 50. Your variables look like this:
Student = [Bob, Johnny]
Mark = [50]
Notice that when your code is validating the grade, there is no Mark[1], because the array only contains one value and i is looking at the second entry - thus NaN. Also, you have more entries in Student than you do in Mark.
As a general principle, you should not "commit" the data until you have finished all your validation logic. So store the entered amounts in temporary variables, check them, and then finally add them to the array at the end once you have good input data:
var entryStudent = prompt("Enter Student Name: ");
var entryMark = parseInt (prompt("Enter Student mark: "));
//Check if Mark entered is not out of bounds and gives a grade
...
//Once you have determined the values are valid, add them to the array
if (valid) {
Student.push(entryStudent);
Mark.push(entryMark);
} else {
// make sure i is moved back to previous entry so you don't skip one
i--;
}
This code isn't complete (for example, you need to figure out how to determine whether valid is true or false), but it should give you the general idea.
I would suggest 2 things -
Make your "isNaN" check before any other checks (so you wouldn't insert wrong values).
Store the parseInt result in a variable, make all the checks on that variable, and only if it passes - push it into Marks. That way you can avoid holding the i reference.
Something like this:
var grade, name;
for (var i = 0; Repeat !== 'n'; i++) {
name = prompt("Enter Student Name: ");
grade = parseInt(prompt("Enter Student mark: "));
// check if grade entered is a number
if (isNaN(grade)) {
alert("Must input numbers");
continue;
}
// check if grade entered is not out of bounds
if (grade < 0 || grade > 100) {
alert("Grade out of bounds");
continue;
}
// store the data
Student.push(name);
Mark.push(grade);
if (grade >= 83) {
getGrade.push("A");
A++;
} else if (grade >= 70) {
getGrade.push("B");
B++;
} else if (grade >= 50) {
getGrade.push("C");
C++;
} else if (grade >= 0) {
getGrade.push("F");
F++;
}
Repeat = prompt("Do you want to enter another student: y/n");
}

Categories