Need a Java IF Statement for Grading System - javascript

I need someone to show me how to try add an IF statement after the user put's in their grade, the statement needs to display the alert right at the end if the mark is greater than 100 or less than 0. I've tried many different things and really not sure how to present this at all. If anyone could show me how to do it would be great.
var mark;
var grade;
grade = "Not Yet Graded";
mark = prompt( "Please input the mark(%)" );
mark = parseInt( mark, 10 ); // see comment
if( mark > 70 )
{
grade = "First Class";
}
else if( mark > 60 )
{
grade = "Upper Second";
}
else if( mark > 50 )
{
grade = "Lower Second";
}
else if( mark > 40 )
{
grade = "Third Class";
}
else if( mark < 40 )
{
grade = "Fail";
}
alert( "Mark: " + mark + "% - Grade: " + grade );
}
else
{
alert( "Invalid mark, outside range 0-100" );
}

You should check your value bounds before you begin grading like
if (mark < 0 || mark > 100)
{
alert('Invalid mark, outside range 0-100');
}
else if (mark > 70)
{
grade = 'First Class';
}
else if (mark > 60)
{
grade = 'Upper Second';
}
else if (mark > 50)
{
grade = 'Lower Second';
}
else if (mark > 40)
{
grade = 'Third Class';
}
else if (mark <= 40)
{
grade = 'Fail';
}
Also, notice that you either need mark >= 40 for third class or mark the user's grade as fail if mark <= 40. Otherwise, you'll miss grading when the score is 40.
At the end, you can simply check if the grade was initialized or not to show the grade alert.
if (grade != null)
{
alert('Mark: ' + mark + '% - Grade: ' + grade);
}

This seems to work:
var mark;
var grade;
grade = "Not Yet Graded";
mark = prompt( "Please input the mark(%)" );
mark = parseInt( mark, 10 ); // see comment
if (mark>100) grade="unclassified";
else if( mark > 70 ) grade = "First Class";
else if( mark > 60 ) grade = "Upper Second";
else if( mark > 50 ) grade = "Lower Second";
else if( mark > 40 ) grade = "Third Class"
else if( mark >= 0 ) grade = "Fail";
else grade="unclassified";
if (grade!="unclassified") alert( "Mark: " + mark + "% - Grade: " + grade );
else alert( "Invalid mark, outside range 0-100" );
It first checks for a mark over 100. All the elseif's will fail as soon as one of the if clause's makes it. It stored 'unclassified' as the grade. The grade of fail is given to any score 0 to 40 inclusive, if this fails, grade is defaulted to unclassified. We now break out of the loop and evaluate grade separately - if it is not 'unclassified' then the mark was valid, and we alert the grade, if 'grade' is equal to 'unclassified' then the alert says so with 'Invalid mark, outside range 0-100'.
One more thing, in JavaScript if there is only one line of code after a comparision, you do not need to use curly brackets {}, so instead of:
else if( mark > 60 ) {grade = "Upper Second";}
we can use:
else if( mark > 60 ) grade = "Upper Second";
(although this isn't true for functions which needs {} regardless of the number of lines in the function body.)

Your code is failing because you are not checking whether the mark is below (or equal to) 100 and above (or equal to) 0. This way if you get 110 you get first class while if you get -10 you get fail.
You just need to make sure that there the mark is smaller or equal to 100 in the first series of if, greater or equal to 0 in the last if, and then before alerting that the mark is once more between 0 and 100 (included) before you print what you want to print. Do it like this :
if( mark > 70 && mark <= 100)
{
grade = "First Class";
}
else if( mark > 60 && mark <= 100)
{
grade = "Upper Second";
}
else if( mark > 50 && mark <= 100)
{
grade = "Lower Second";
}
else if( mark > 40 && mark <= 100)
{
grade = "Third Class";
}
else if( mark < 40 && mark >= 0)
{
grade = "Fail";
}
if (mark <= 100 && mark >= 0) {
alert( "Mark: " + mark + "% - Grade: " + grade );
}
else
{
alert( "Invalid mark, outside range 0-100" );
}
OR You could also do (checking if the mark is between 0 and 100 only in the beginning):
if (mark >= 0 && mark <= 100) {
if( mark > 70)
{
grade = "First Class";
}
else if( mark > 60)
{
grade = "Upper Second";
}
else if( mark > 50)
{
grade = "Lower Second";
}
else if( mark > 40)
{
grade = "Third Class";
}
else if( mark < 40)
{
grade = "Fail";
}
}
else {
alert( "Invalid mark, outside range 0-100" );
}
if (mark <= 100 && mark >= 0) {
alert( "Mark: " + mark + "% - Grade: " + grade );
}
By the way this is not Java, if you want Java then replace alert with System.out.println ...

Related

JS: Grading System of a school Any Fix (Error== undefined) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
A school has the following rules for the grading system:
// a. 45 to 50 - D
// b. 50 to 60 - C
// c. 60 to 80 - B
// d.Above 80 - A
Ask the user to enter marks, name as well as Roll No and print the corresponding grade
const school_grading_system = () => {
let student_details = {
name_of_student: prompt("Enter your name:"),
roll_number_of_student: Number(prompt("Enter your Roll No: ")),
marks_of_student: Number(prompt("Enter your marks out of 100: ")),
percentage_obtained_student: function() {
return ((this.marks_of_student / 100) * 100)
}
}
if (this.percentage_obtained_student >= 80 && this.percentage_obtained_student < 80) {
console.log(`${this.percentage_obtained_student}:Good Job! You have scored A Grade`)
} else if (this.percentage_obtained_student >= 60 && this.percentage_obtained_student < 60) {
console.log(`${this.percentage_obtained_student}: Good! You have obtained B Grade`)
} else if (this.percentage_obtained_student >= 50 && this.percentage_obtained_student < 60) {
console.log(`${this.percentage_obtained_student}: Good! You have obtained C Grade`)
} else if (this.percentage_obtained_student >= 45 && this.percentage_obtained_student < 50) {
console.log(`${this.percentage_obtained_student}: Good! You have obtained D Grade`)
}
}
console.log(school_grading_system())
// Rule 1: Kinda keep it simple
// As total marks are going to be 100 so no need for a percentage method
const school_grading_system = () => {
let student_details = {
name_of_student: prompt("Enter your name:"),
roll_number_of_student: Number(prompt("Enter your Roll No: ")),
marks_of_student: Number(prompt("Enter your marks out of 100: "))
}
if (student_details.marks_of_student >= 45 && student_details.marks_of_student < 50) {
return "Grade D"
} else if (student_details.marks_of_student >= 50 && student_details.marks_of_student < 60) {
return "Grade C"
} else if (student_details.marks_of_student >= 60 && student_details.marks_of_student < 80) {
return "Grade B"
} else if (student_details.marks_of_student >= 80 && student_details.marks_of_student <= 100) {
return "Grade A"
}
}
console.log(school_grading_system())
// Note: I have not displayed the name and marks stuff because I hope you are capable enough to do that so I am leaving that upon you
There are some problems within your code that lead to the result being wrong, let's break them down:
The use of this keyword in your school_grading_system (outside the student_details object) is the window object and NOT student_details object so when you try this.percentage_obtained_student that is translated to window.percentage_obtained_student and as window dosen't have an attribute called percentage_obtained_student the result of that call would be undefined that lead to deliver the wrong results. So instead of this.percentage_obtained_student you should use student_details.percentage_obtained_student to get the needed piece of data.
Another issue is the your conditions found on the if .. else statements. Let's imagine a student having 80 as his score, when you say student_details.percentage_obtained_student >= 80 && student_details.percentage_obtained_student < 80 this condition will never be satisfied because it negates itself as that conditon translates to IF the SCORE is greater than or equal to 80 AND the score is less than 80 but we cannot have a number bigger or equal and lower than itself at the same time (I couldn't describe more accurately).
With that being said, here's a corrected version of your code:
const school_grading_system = () => {
let student_details = {
name_of_student: prompt("Enter your name:"),
roll_number_of_student: Number(prompt("Enter your Roll No: ")),
marks_of_student: Number(prompt("Enter your marks out of 100: ")),
}
/** the conditons are now refined */
if (student_details.marks_of_student >= 80) {
console.log(`${student_details.marks_of_student}:Good Job! You have scored A Grade`)
} else if (student_details.marks_of_student >= 60) {
console.log(`${student_details.marks_of_student}: Good! You have obtained B Grade`)
} else if (student_details.marks_of_student >= 50) {
console.log(`${student_details.marks_of_student}: Good! You have obtained C Grade`)
} else if (student_details.marks_of_student >= 45) {
console.log(`${student_details.marks_of_student}: Good! You have obtained D Grade`)
}
}
school_grading_system();
By the way, you function has some unhandled cases, to mention some, it doesn't take into consideration the case of a score LESS THAN 45. Also, it doesn't handle wrong user inputs like when the user types a number higher than 100.
Here is a shorter way of doing the grading work:
// 45 to 50 - D
// 50 to 60 - C
// 60 to 80 - B
// Above 80 - A
const grades=[[101,"*** impossible - you must have cheated!"],[80,"A"],[60,"B"],[50,"C"],[45,"D"],[0,"E or below"]];
[95,23,57,-5,45,83,110,74,62].forEach(s=>
console.log(`your score of ${s} gets you the grade ${(grades.find(([g])=>s>=g)??[0,"below ZERO"])[1]}`))

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"

Different cases for the same (or maybe not really) 'if' condition

I was recently passing JS test and one interesting thing i saw is that the 2 statements:
if( x <= 100 ) {...}
if( !(x > 100) ) {...}
Are not the same. In the way, that there are special values existing that'll trigger only one of the following statements.
The question is why and what are those values?
You should look for edges cases like:
let x = undefined;
if( x <= 100 ){
console.log("case one")
}
if( !(x > 100) ) {
console.log("case two")
}
or
let x = "Foo bar";
if( x <= 100 ){
console.log("case one")
}
if( !(x > 100) ) {
console.log("case two")
}
or
let x = NaN
if( x <= 100 ){
console.log("case one")
}
if( !(x > 100) ) {
console.log("case two")
}

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"
}

How to display error message when using a grade calculator in JavaScript?

Below is a grade calculator that will attach a letter grade to the number entered, using if/else statements. I am having trouble finding a way to display an error message if an out of ranger number or non numeric value is entered. Any suggestions? Thanks!
var entry;
var letterGrade;
entry = prompt("Enter number grade from 0 through 100\n" +
"Or enter 999 to end entries", 999);
entry = parseInt(entry);
if (entry <= 59)
letterGrade = "F";
else if (entry >= 60 && entry <= 69)
letterGrade = "D";
else if (entry >= 70 && entry <= 79)
letterGrade = "C";
else if (entry >= 80 && entry <= 89)
letterGrade = "B";
else if (entry >= 90 && entry <= 100)
letterGrade = "A";
alert("Number grade = " + entry + "\n" +
"Letter grade = " + letterGrade);
Well your out of range would be anything >100 so you can cover that with an else in the end:
[..]
else if (entry >= 90 && entry <= 100)
letterGrade = "A";
else
alert("Error, your number " + entry + " was out of range (>100)");
As for it not being a number, you can use isNaN():
if(isNaN(entry)){
alert("That was not a number!");
else {
if (entry <= 59)
letterGrade = "F";
....
}
Edit: I see your input is >0<101 so to catch negative numbers you would need to add this to your first if statement:
if (entry >= 0 && entry <= 59)
Add a check in the beginning to see if entry is a valid input:
if(isNaN(entry) || entry < 0 || entry > 100)
alert('Only a grade between 0 and 100 is allowed');
var entry
, letterGrade;
entry = parseInt(prompt("Enter number grade from 0 through 100\n" +
"Or enter 999 to end entries", 999));
if(isNaN(entry) || entry < 0)
alert('Only a grade between 0 and 100 is allowed');
else if (entry <= 59)
letterGrade = "F";
else if (entry >= 60 && entry <= 69)
letterGrade = "D";
else if (entry >= 70 && entry <= 79)
letterGrade = "C";
else if (entry >= 80 && entry <= 89)
letterGrade = "B";
else if (entry >= 90 && entry <= 100)
letterGrade = "A";
alert("Number grade = " + entry + "\n" +
"Letter grade = " + letterGrade);

Categories

Resources