If statement does not repeat when condition is met? - javascript

I want the script to keep prompting the user for a valid input which is from 0 to 100 but can't get it to work. I am more confused than when I started to work on this script last night. This is my homework and the teacher has asked us to use if statement that is why I haven't tried to use the while loop but maybe I should.
Here is the code.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Grade</title>
<script type="text/javascript">
var grade = Number(prompt("What did you score: ", "Your Score Here!"));
if (grade < 0 || grade > 100) {
grade = Number(prompt("Please enter a valid score", "Your Score Here!"));
} else if (grade >= 0 && grade < 60) {
grade = "F";
} else if (grade >= 60 && grade < 70) {
grade = "D";
} else if (grade >= 70 && grade < 80) {
grade = "C";
} else if (grade >= 80 && grade < 90) {
grade = "B";
} else if (grade >= 90 && grade <= 100) {
grade = "A";
}
document.write("<strong>Your grade is:</strong> " + grade);
</script>
</head>
<body>
</body>
</html>

Yes you would use a while loop. In this case you would have a flag that checks if the input is invalid. We can assume it's valid in the loop, and when the invalid check goes through change it to being invalid (false), and cause the loop to repeat.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Grade</title>
<script type="text/javascript">
var grade = Number(prompt("What did you scrore: ", "Your Score Here!"));
var valid = false;
while(!valid)
{
valid = true; // assume it's valid
if (grade < 0 || grade > 100) {
grade = Number(prompt("Please enter a valid score", "Your Score Here!"));
valid = false; // It it happens to not be valid, change it to invalid
} else if (grade >= 0 && grade < 60) {
grade = "F";
} else if (grade >= 60 && grade < 70) {
grade = "D";
} else if (grade >= 70 && grade < 80) {
grade = "C";
} else if (grade >= 80 && grade < 90) {
grade = "B";
} else if (grade >= 90 && grade <= 100) {
grade = "A";
}
}
document.write("<strong>Your grade is:</strong> " + grade);
</script>
</head>
<body>
</body>
</html>

Related

Grade Conversion in HTML

So, I have been working on this code for class, and everything I have done never seems to work! My work is in Visual Code Studio, and it does not bring up any sort of errors. I've looked it up and everything, and I just can't figure out why I can't get an output!
It is a grade conversion. By reading my code I guess you can figure out the parameters of the conversion. I just can't seem to figure out what is going on!
<!DOCTYPE HTML>
<html>
<pre>
<body>
<script>
var grade=95;
if ((grade >= 90) (and) (grade <= 100)) {
document.write("A+ -- Exceptional!");
} else if ((grade >= 80) (and) (grade <= 89)) {
document.write("A -- Excellent!");
} else if ((grade >= 70) (and) (grade <= 79)) {
document.write("B -- Good!");
} else if ((grade >= 60) (and) (grade <= 69)) {
document.write("C -- Satisfactory");
} else if ((grade >= 50) (and) (grade <= 59)) {
document.write("D -- Barely Acceptable");
} else if ((grade >= 0) (and) (grade <= 49)) {
document.write("F -- Failure");
} else {
document.write("An accepted grade was not implemented into the system.");
}
</script>
</body>
</pre>
</html>
and is not a javascript operator.
Replace every (and) with &&
var grade = 95;
if (grade >= 90 && grade <= 100) {
document.write("A+ -- Exceptional!");
} else if (grade >= 80 && grade <= 89) {
document.write("A -- Excellent!");
} else if (grade >= 70 && grade <= 79) {
document.write("B -- Good!");
} else if (grade >= 60 && grade <= 69) {
document.write("C -- Satisfactory");
} else if (grade >= 50 && grade <= 59) {
document.write("D -- Barely Acceptable");
} else if (grade >= 0 && grade <= 49) {
document.write("F -- Failure");
} else {
document.write("An accepted grade was not implemented into the system.");
}
Also you should not have <pre> tags outside of the <body>

How can I improve my code, and why does it not run?

This code is meant to take a number score from 0 to 100 and print the grade.
This is for school and is using a simplified version of javascript from the website 'codehs.com' I've been stuck on this for a while now, I would like help fixing my code.
/* This code is meant to take a number score from 0 to 100 and print
the grade. */
function start(){
/*given list */
lettergrade(100);
lettergrade(83);
lettergrade(68);
lettergrade(91);
lettergrade(47);
lettergrade(79);
}
/* this will print the grades above by using If/else if statements */
function lettergrade(score){
if(score = 90-100){
return("A");
}
else if(score = 80-90){
return("B");
}
else if(score = 70-79){
return("C");
}
else if(score = 60-69){
return("D");
}
else if(score = 0-59){
return("F");
}
}
The Expected result is to print the letter grades, A-F and the +/- sign if needed, but the code does not run.
There were multiple places wrong with your code:
lettergrade(100) is wrong because your function defined as letterGrade, there is case sensitivity in JS
if(score = 90-99) is wrong because if statement is expecting expression which you can choose to use == or ===. Single equal sign = meant for value assignment, not for comparison. And 90-99 is wrong, that is calculation not range. Correct way should be if(score >= 90 && score <= 99)
/* this will print the grades above by using If/else if statements */
function letterGrade(score){
if(score >= 90 && score <= 99){
return("A");
}
else if(score >= 80 && score < 90){
return("B");
}
else if(score >= 70 && score < 80){
return("C");
}
else if(score >= 60 && score < 70){
return("D");
}
else if(score >= 0 && score < 60){
return("F");
}
}
function start(){
/*given list */
console.log(letterGrade(100));
console.log(letterGrade(83));
console.log(letterGrade(68));
console.log(letterGrade(91));
console.log(letterGrade(47));
console.log(letterGrade(79));
}
start();
The syntax is full of errors
Watch out for case sensitivity
You want an else statement to check if score is not valid
function letterGrade(score){
if(score >= 90 && score <= 100) {
return "A";
}
else if(score >= 80 && score < 90){
return "B";
}
else if(score >= 70 && score <= 79){
return "C";
}
else if(score >= 60 && score <= 69){
return "D";
}
else if(score >= 0 && score <= 59){
return "F";
}
else {
console.error(`Err: ${score} is not a valid score`);
}
}
Normal usage :
console.log(letterGrade(85)); // "B"
console.log(letterGrade(100)); // "A"
console.log(letterGrade(1)); // "F"
Handle errors :
console.log(letterGrade(4242)); // "Err: 4242 is not a valid Score"
console.log(letterGrade(-42)); // "Err: -42 is not a valid Score"
console.log(letterGrade("Hello World!")); // "Err: "Hello World!" is not a valid Score"

My code keeps returning undefined underneath the output

My JavaScript function keeps returning undefined underneath the correct output value.
let grade;
function getGrade(score) {
// Write your code here
if (score >= 25 && score <= 30) {
console.log('A');
}
else if (score >= 20 && score <= 25) {
console.log('B');
}
else if (score >= 15 && score <= 20) {
console.log('C');
}
else if (score >= 10 && score <= 15) {
console.log('D');
}
else if (score >= 5 && score <= 10) {
console.log('E');
}
else {
console.log('F');
}
return grade;
}
You haven't defined your grade. And it will always be undefined.
One way to do it is as follows:
function getGrade(score) {
var grade = "";
// Write your code here
if (score >= 25 && score <= 30) {
grade = "A";
}
else if (score >= 20 && score <= 25) {
grade = "B";
}
else if (score >= 15 && score <= 20) {
grade = "C";
}
else if (score >= 10 && score <= 15) {
grade = "D";
}
else if (score >= 5 && score <= 10) {
grade = "E";
}
else {
grade = "F";
}
return grade;
}
console.log(getGrade(27))
It seems you have return grade; at the bottom, but grade doesn't seem to be defined anywhere.
You should to set your variable "grade" value, or just delete
return grade;
Always check the console. It's currently singing at you, telling you grade is undefined.
You're trying to return something you haven't assigned a value to.
function getGrade(score) {
// ... //
return grade; //<-- nowhere do you define grade
}
Should be
function getGrade(score) {
let grade;
if (score >= 25 && score <= 30) grade = 'A';
else if (score >= 20 && score <= 25) grade = 'B';
else if (score >= 15 && score <= 20) grade = 'C';
else if (score >= 10 && score <= 15) grade = 'D';
else if (score >= 5 && score <= 10) grade = 'E';
else grade = 'F';
console.log(grade);
return grade;
}
Use return instead of console.log()
function getGrade(score) {
if (score >= 25 && score <= 30) {
return 'A'
}
else if (score >= 20 && score <= 25) {
return 'B'
}
else if (score >= 15 && score <= 20) {
return 'C';
}
else if (score >= 10 && score <= 15) {
return 'D';
}
else if (score >= 5 && score <= 10) {
return 'E';
}
else {
return 'F';
}
}
console.log(getGrade(20))
As there is difference of 5 b/w each grade range so you can use division and Math.floor
function getGrade(score) {
let grades = 'FEDCBA'
return score === 30 ? 'A' : grades[Math.floor((score)/5)]
}
console.log(getGrade(20))
console.log(getGrade(19))
console.log(getGrade(30))

Creating an input form with javascript

I had a question about creating a form that I can input "grades" into which also would check to see if those grades were between 0 and 25 or 0 and 100 (input validation). My code has to be in javascript but I don't know where or how to start. In other words, I need to take this code and add a "form" and check for valid input. This is what I have so far:
<!doctype html>
<html>
<script>
var a1=parseFloat(prompt("Enter the grade for assignment 1: "));
var a2=parseFloat(prompt("Enter the grade for assignment 2: "));
var a3=parseFloat(prompt("Enter the grade for assignment 3: "));
var a4=parseFloat(prompt("Enter the grade for assignment 4: "));
var mid=parseFloat(prompt("Enter the grade for the mid exam: "));
var fe=parseFloat(prompt("Enter the grade for the final exam: "));
var fp=parseFloat(prompt("Enter the grade for the final project: "));
var sum;
var grade;
var error;
sum=((a1+a2+a3+a4)/4)*(4*0.25)+(mid*0.25)+(fe*0.25)+(fp*0.25);
/* if (a1 < 0 && a1 > 25) {
error = window.prompt( "Assignments are only out of 25 points, please re-enter the integer grade:")
} */
if (sum >= 94.0) {
grade = "A";
} else if (sum <= 94.0 && sum >= 90.0) {
grade = "A-";
} else if (sum <= 90.0 && sum >= 87.0) {
grade = "B+";
} else if (sum <= 86.9 && sum >= 84.0) {
grade = "B";
} else if (sum <= 83.9 && sum >= 80.0) {
grade = "B-";
} else if (sum <= 79.9 && sum >= 77.0) {
grade = "C+";
} else if (sum <= 76.9 && sum >= 74.0) {
grade = "C";
} else if (sum <= 73.9 && sum >= 70.0) {
grade = "C-";
} else if (sum <= 69.9 && sum >= 67.0) {
grade = "D+";
} else if (sum <= 66.9 && sum >= 64.0) {
grade = "D";
} else if (sum <= 63.9 && sum >= 60.0) {
grade = "D-";
} else if (sum <= 60.0) {
grade = "F";
}
document.writeln("The final percent grade is "+sum+"%. Your grade letter is: "+grade+".");
</script>
</html>
Take the values from textboxes and give a button get Results and display the result in the output div.
Here is how I have done.
In javascript, take values from the textboxes using document.getElementById("<ID>").value and store it in a variable. Follow the same step for all the input boxes. And process the values obtained from textboxes and display it when the button is clicked.
Here is a simple code snippet which does the same thing using fields.
function myFunction()
{
var a1 = parseFloat(document.getElementById("a1").value);
var a2 = parseFloat(document.getElementById("a2").value);
var a3 = parseFloat(document.getElementById("a3").value);
var a4 = parseFloat(document.getElementById("a4").value);
var mid = parseFloat(document.getElementById("mid").value);
var fe = parseFloat(document.getElementById("fe").value);
var fp = parseFloat(document.getElementById("fp").value);
var sum=((a1+a2+a3+a4)/4)*(4*0.25)+(mid*0.25)+(fe*0.25)+(fp*0.25);
var grade;
if (sum >= 94.0) {
grade = "A";
} else if (sum <= 94.0 && sum >= 90.0) {
grade = "A-";
} else if (sum <= 90.0 && sum >= 87.0) {
grade = "B+";
} else if (sum <= 86.9 && sum >= 84.0) {
grade = "B";
} else if (sum <= 83.9 && sum >= 80.0) {
grade = "B-";
} else if (sum <= 79.9 && sum >= 77.0) {
grade = "C+";
} else if (sum <= 76.9 && sum >= 74.0) {
grade = "C";
} else if (sum <= 73.9 && sum >= 70.0) {
grade = "C-";
} else if (sum <= 69.9 && sum >= 67.0) {
grade = "D+";
} else if (sum <= 66.9 && sum >= 64.0) {
grade = "D";
} else if (sum <= 63.9 && sum >= 60.0) {
grade = "D-";
} else if (sum <= 60.0) {
grade = "F";
}
document.getElementById("result").innerHTML = ("The final percent grade is "+sum+"%. Your grade letter is: "+grade+".");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
a1: <input type="text" id="a1"><br><br>
a2: <input type="text" id="a2"><br><br>
a3: <input type="text" id="a3"><br><br>
a4: <input type="text" id="a4"><br><br>
mid: <input type="text" id="mid"><br><br>
finalexam: <input type="text" id="fe"><br><br>
finalproject: <input type="text" id="fp"><br><br>
<button onclick="myFunction()">Get Results</button><br><br>
<span id="result"></span>
</body>
</html>
Thank you.

Using JS i need to create a Average variable

hi i need to create a Average variable that will average out my grades any help will be greatly appreciated i have the following. but i cant figure out the average portion of it
my code works for the inputs and gets the grades, and i also have the html portion
and i have an empty p tag for all of the inner html
function myFunction(){
let math = document.getElementById("math").value;
let science = document.getElementById("science").value;
let history = document.getElementById("history").value;
let english = document.getElementById("english").value;
let average = ( [ "math","science","history","english", ] );
// this is match sec
if(math >= 90) {
document.getElementById("mathG").innerHTML = "Your Grade is A"
}
else if (math >= 80 && math < 90) {
document.getElementById("mathG").innerHTML = "Your Grade is B"
}
else if (math >= 70 && math < 80) {
document.getElementById("mathG").innerHTML = "Your Grade is c"
}
else if (math >= 60 && math < 70) {
document.getElementById("mathG").innerHTML = "Your Grade is d"
}
else {
document.getElementById("mathG").innerHTML = "Your Grade is F"
}
// Science section
if(science >= 90) {
document.getElementById("scienceG").innerHTML = "Your Grade is A"
}
else if (science >= 80 && science < 90) {
document.getElementById("scienceG").innerHTML = "Your Grade is B"
}
else if (science >= 70 && science < 80) {
document.getElementById("scienceG").innerHTML = "Your Grade is c"
}
else if (science >= 60 && science < 70) {
document.getElementById("scienceG").innerHTML = "Your Grade is d"
}
else {
document.getElementById("scienceG").innerHTML = "Your Grade is F"
}
// History
if(history >= 90) {
document.getElementById("historyG").innerHTML = "Your Grade is A"
}
else if (history >= 80 && history < 90) {
document.getElementById("historyG").innerHTML = "Your Grade is B"
}
else if (history >= 70 && history < 80) {
document.getElementById("historyG").innerHTML = "Your Grade is c"
}
else if (history >= 60 && history < 70) {
document.getElementById("historyG").innerHTML = "Your Grade is d"
}
else {
document.getElementById("historyG").innerHTML = "Your Grade is F"
}
//English
english
if(english >= 90) {
document.getElementById("englishG").innerHTML = "Your Grade is A"
}
else if (english >= 80 && english < 90) {
document.getElementById("englishG").innerHTML = "Your Grade is B"
}
else if (english >= 70 && english < 80) {
document.getElementById("englishG").innerHTML = "Your Grade is c"
}
else if (english >= 60 && english < 70) {
document.getElementById("englishG").innerHTML = "Your Grade is d"
}
else {
document.getElementById("englishG").innerHTML = "Your Grade is F"
}
The code will be like this I guess :
let average = math + science + history + english / 4;
Here you will get the average and with the if else like you did for getting grades for each subject you can find the average grade as well.
if(average >= 90) {
average = "A";
}
Tip: You can use loop or map to reduce the line of code.
A few things:
First, make sure to cast your inputs to a number. It works with strings when doing a comparison with > or <, but if you try to add strings together with +, it will concatenate them rather then summing their numeric values.
Second, you can shorten your code by putting the duplicated if/else chains into a function.
Anyway, an average is just a sum divided by the number of summed items, so:
let average = (math + science + history + english) / 4;
would work. Or you can use a reduce if you have them in an array. This might come in handy if you frequently add or remove subjects:
let scores = [math, science, history, english];
let average = scores.reduce((total, score) => total + score) / scores.length;
Anyway, here's a snippet that seems to be working how you want:
function calculateAllGrades() {
let math = Number(document.getElementById("math").value);
let science = Number(document.getElementById("science").value);
let history = Number(document.getElementById("history").value);
let english = Number(document.getElementById("english").value);
// let average = ( [ "math","science","history","english", ] );
// Hardcoded, okay if these are all subjects:
let average = (math + science + history + english) / 4;
// Or if they change, you can use an array, easier if they change or you add more:
let scores = [math, science, history, english]
average = scores.reduce((sum, score) => sum + score) / scores.length
function calculateGrade(score, elementID) {
const element = document.getElementById(elementID);
if (score >= 90) {
element.innerHTML = "Your Grade is A";
} else if (score >= 80) {
element.innerHTML = "Your Grade is B";
} else if (score >= 70) {
element.innerHTML = "Your Grade is C";
} else if (score >= 60) {
element.innerHTML = "Your Grade is D";
} else {
element.innerHTML = "Your Grade is F";
}
}
calculateGrade(math, "mathG")
calculateGrade(science, "scienceG")
calculateGrade(history, "historyG")
calculateGrade(english, "englishG")
calculateGrade(average, "averageG")
}
let button = document.getElementById("button")
button.addEventListener("click", calculateAllGrades)
<div>MATH:<input type="text" id="math" /></div>
<div>SCIENCE:<input type="text" id="science" /></div>
<div>HISTORY:<input type="text" id="history" /></div>
<div>ENGLISH:<input type="text" id="english" /></div>
<br />
<div>MATH:<div id="mathG"></div></div><br/>
<div>SCIENCE:<div id="scienceG"></div></div><br/>
<div>HISTORY:<div id="historyG"></div></div><br/>
<div>ENGLISH:<div id="englishG"></div></div><br/>
<div>AVERAGE:<div id="averageG"></div></div><br/>
<button id="button">Calculate</button>
history is a global in browsers, so you can't use it as a variable name.
You should do something like:
let mathGrade = document.getElementById("math").value;
let scienceGrade = document.getElementById("science").value;
let historyGrade = document.getElementById("history").value;
let englishGrade = document.getElementById("english").value;
let average = (mathGrade + scienceGrade + historyGrade + englishGrade) / 4
Then, if you want the 'average' letter grade, you can do something similar to what you did for the other grades using the average:
if(average >= 90) {
document.getElementById("averageG").innerHTML = "Your Average Grade is A"
}
else if (average >= 80 && average < 90) {
document.getElementById("averageG").innerHTML = "Your Average Grade is B"
}
else if (average >= 70 && average < 80) {
document.getElementById("averageG").innerHTML = "Your Average Grade is c"
}
else if (average >= 60 && average < 70) {
document.getElementById("averageG").innerHTML = "Your Average Grade is d"
}
else {
document.getElementById("averageG").innerHTML = "Your Average Grade is F"
}

Categories

Resources