In my program I am using a do-while loop to prompt for grades until a -1 is entered and then increments the amount of grades inputted. A while loop then checks if the grade isNaN or less then 0 or greater then 100. The program will ask for another grade if so. If a -1 is entered the program will break from the loop and calculate the average based on the counter for the grades and the total number of grades added together. When I run the program and put in a negative 1 to stop it prints the -1 inside of the table and the semester average displays as NaN. I am assuming this is because the negative -1 makes it not a non positive number but I am unsure how to fix this.
Here is my code.
do {
grade = prompt('Enter grade(-1 to stop)');
count++;
while (grade < -1 || grade > 100 || isNaN(grade)) {
grade = prompt('Enter grade again (-1 to stop)');
}
document.write('<td>Grade ' + count + '</td>');
document.write('<td width="50"> ' + grade + ' </td>');
document.write('</tr>');
}
while (grade != -1) {
--total;
alert("You have input -1 to stop");
document.write('</table>');
}
total = total + grade;
avg = total / count;
document.write('Semester Average: ' + avg + '<br /><br />');
I tried to fix your problem here
https://jsfiddle.net/51v3qft9/26/
This is the snippet which may not be correct as your logic but it works for me
var count = 0
var total = 0
var avg = 0
document.write('<table>');
do {
grade = prompt('Enter grade(-1 to stop)');
//if user key-in nothing, we need to ask user to key-in again
while (!grade || grade < -1 || grade > 100 || isNaN(grade)) {
grade = prompt('Enter grade again (-1 to stop)');
}
//whenever user key-in -1, we need to break `while`
if (grade == -1) {
break
}
count++;
document.write('<td>Grade ' + count + '</td>');
document.write('<td width="50"> ' + grade + ' </td>');
document.write('</tr>');
total += Number(grade); // you need to convert `grade` to number
} while (grade != -1)
alert("You have input -1 to stop");
document.write('</table>');
if(count > 0) {
avg = total / count;
}
document.write('Semester Average: ' + avg + '<br /><br />');