Hi everybody,

I am new to JavaScript and need help to start, please help to Write the script to calculate grades. Up to 10 scores can be entered. The raw scores are curved and grades are assigned. Click the "Load" button to work with the example scores. If the average is below 75, make it 75.

Assume the following 10 scores: 40, 46, 48, 56, 62, 64, 66, 70, 76, and 78. Enter the scores and press button Load. The average will be given as 60.5 ~61 so we have to add 14 (75-61) to every score. This is done by pressing button Curve.


Assume that the grades are assigned as follows: 90-100 = A, 80-89 = B, 70-79 = C, 60-69 = D, below 60 = F. The grade will be displayed by pressing button Grades.


Your help is much much appreciated.

Regards :cry:

Dani AI

Generated

This thread requests a small JavaScript page to accept up to 10 test scores, compute the average, apply a uniform curve so the class average is at least 75 (the OP uses rounding: 60.5 → 61), then assign letter grades (90–100 A, 80–89 B, 70–79 C, 60–69 D, <60 F). provided the requirements and offered a useful scaffold; the approach below clarifies the algorithm, avoids common pitfalls (form submission reloads, non-numeric input, scores >100), and implements the requested “Load → Curve → Grades” flow.

Recommended algorithm in three steps:

  1. Parse and validate up to 10 numeric scores (ignore blanks, reject non-numeric tokens, clamp each score to 0–100).
  2. Compute the average, use Math.round to match the OP’s convention, and if rounded average < 75 compute delta = 75 − roundedAvg; add that delta to every score and clamp each result at 100.
  3. Map final scores to letters using the stated ranges.

Example (minimal, copy into a .html file and open in a browser):

<!doctype html>
<html>
<body>
<textarea id="scores" rows="3" cols="50" placeholder="Enter up to 10 scores, comma-separated"></textarea>
<br/>
<button type="button" id="load">Load Example</button>
<button type="button" id="curve">Curve</button>
<button type="button" id="grades">Grades</button>

<pre id="output"></pre>

<script>
(function(){
  const example = "40,46,48,56,62,64,66,70,76,78";
  const scoresEl = document.getElementById('scores');
  const out = document.getElementById('output');

  function parseScores(){
    const parts = scoresEl.value.split(',').map(s=>s.trim()).filter(s=>s!=='');
    if (parts.length === 0) return [];
    if (parts.length > 10) return 'TOO_MANY';
    const nums = parts.map(Number);
    if (nums.some(n => !Number.isFinite(n))) return 'BAD_INPUT';
    return nums.map(n => Math.max(0, Math.min(100, n)));
  }

  function avg(arr){ return arr.reduce((a,b)=>a+b,0)/arr.length; }

  function applyCurve(arr){
    const rounded = Math.round(avg(arr));
    if (rounded >= 75) return arr.slice();
    const delta = 75 - rounded;
    return arr.map(s => Math.min(100, s + delta));
  }

  function letter(s){
    if (s>=90) return 'A';
    if (s>=80) return 'B';
    if (s>=70) return 'C';
    if (s>=60) return 'D';
    return 'F';
  }

  document.getElementById('load').addEventListener('click', ()=> {
    scoresEl.value = example;
    out.textContent = 'Example loaded.';
  });

  document.getElementById('curve').addEventListener('click', ()=> {
    const parsed = parseScores();
    if (parsed === 'TOO_MANY') { out.textContent = 'Maximum 10 scores allowed.'; return; }
    if (parsed === 'BAD_INPUT') { out.textContent = 'Non-numeric value found.'; return; }
    if (parsed.length === 0) { out.textContent = 'No scores provided.'; return; }
    const curved = applyCurve(parsed);
    out.textContent = 'Curved scores: ' + curved.join(', ') + '\\nAverage: ' + (avg(curved).toFixed(2));
    scoresEl.value = curved.join(', ');
  });

  document.getElementById('grades').addEventListener('click', ()=> {
    const parsed = parseScores();
    if (parsed === 'TOO_MANY') { out.textContent = 'Maximum 10 scores allowed.'; return; }
    if (parsed === 'BAD_INPUT') { out.textContent = 'Non-numeric value found.'; return; }
    if (parsed.length === 0) { out.textContent = 'No scores provided.'; return; }
    out.textContent = parsed.map((s,i)=> '#' + (i+1) + ': ' + s + ' -> ' + letter(s)).join('\\n');
  });
})();
</script>
</body>
</html>

Troubleshooting and notes: files created in Notepad must be saved with an .html extension (Save As → All Files) before opening in a browser. Use buttons with type="button" (not submit) to avoid unwanted page reloads. The example uses Math.round so the given scores produce average ≈60.5 → 61, delta = 14, and each score gets +14 (capped at 100). The array/reduce approach implements the same ideas that suggested (tracking total and count) but keeps the logic compact and easier to test.

I do not wish to do your homework for you but i will give you a start :}

Look at my problem i posted. that works fine for taking in a numeric value and adding it to another value. you want to create additional variables called 'total' and 'scores entered' or something like that and rather than set the value to form element like i am doing in my function, you want to add the value to total every time the fuction is called (maybe you have 2 buttons, one is enter test score, and another is grade)

so you collect all your test scores and click grade which calls a grade function that looks at total/scores enterd to give the average and converts it to a letter grade (use if statements)

that should be a good start. try something, post some code and i will help you more.

I appreciate your help, but my knowledge to JavaScrip is "0", even i don't know how to start, I use notepad and save it as HTML. I tried it but it didn't work. below is class-average example:

import javax.swing.JOptionPane;

   public class Average1 {

      public static void main( String args[] ) 
      {
         int total;          // sum of grades input by user
        int gradeCounter;   // number of grade to be entered next
        int grade;          // grade value
        int average;        // average of grades

        String gradeString; // grade typed by user

        // initialization phase
        total = 0;          // initialize total
        gradeCounter = 1;   // initialize loop counter

        // processing phase
        while ( gradeCounter <= 10 ) {  // loop 10 times

           // prompt for input and read grade from user
           gradeString = JOptionPane.showInputDialog(
              "Enter integer grade: " );

           // convert gradeString to int
           grade = Integer.parseInt( gradeString );

Please help me to do this, I can't even start.

Regards

That looks like java. Are you trying to do this in java or as a javascript in an html page?

I will look into a base page to post up in a bit. I am assuming you are doing this in an html page using javascript.

Yes, I am doing html page using javascript.

regards

ok, I hope i am not too late. I did not check this over weekend.

here is a start. It has many bugs, but like i said, I want you to learn from this so you need to figure things out. I used to teach at college so I can't just give it to you.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  
<title>quick sample for someone</title>

<script language="JavaScript">
/***************************************************************
* Function: isValidFloat(num)								   
* Description: This function will check for a valid Float
****************************************************************/
function isValidFloat(num)
{	  
    var valid = "0123456789.";
	var temp;
	var decimalPointCount=0;
	
	for (var i = 0; i < num.length; i++)
	{
		temp = num.substring(i, i + 1);
		if(temp==".")
			decimalPointCount++;
		if (decimalPointCount > 1)
		{
			return false;
		}
		if (valid.indexOf(temp) == "-1")
		{		
			return false;
		}
	}
	return true;
}  



nTotalScores = 0;
nNumberOfScores =0;

function getScores(num){
nTotalScores = nTotalScores + num;
nNumberOfScores = nNumberOfScores + 1;

}




function getGrade( ) {
	var returnGrade = '';
	
	
	 
	if(  )
		alert("the grade is" + )
	else if(  )
		alert("The )
	else if(  ) 
		alert("")
	else if(  ) 
			alert("A Product Price 2 must have an Effective Date. Please select a second Effective Date.")
			
		    
	else returnGrade = 'f'
	return returnGrade 	
}	


/***************************************************************

* Function: trim(str)                                                                                               

* Description: This function will trim the spaces in a string

****************************************************************/

function trim(str) { 

            //Remove leading spaces...

            while (str.substring(0,1) == ' ') {

                        str = str.substring(1, str.length);

            }

 

            //Remove trailing spaces...

            while (str.substring(str.length-1, str.length) == ' ') {

                        str = str.substring(0, str.length-1);

            }

 

    return str;

}




</script>

<META name="GENERATOR" content="IBM WebSphere Studio">
</head>

 <body>
<form name ="someForm">
<table>
<TR ><TD> enter a score and click button </td><td><td><input type="text" name ="something"> <input type="submit"  onclick="Javascript:getScores(document.someForm.something);" > </td></tr>
</table>
</form>
</body>
</html>

Was that of any benefit? I think it gives you almost everything you need to do the problem specified. Please ask any questions. I would like to help, but i do not want to do your work for you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.