java - Trying to calculate the average of inputs given using do-while and while loop but it keeps stopping -
the main gist of script keep asking grades until user inputs negative number. once negative number has been input, calculates average of grades. grade input user can 4-10.
i've been hours trying figure out.. if enter invalid inputs or valid inputs works fine, second try mix script stops.
for example: if enter 4(valid input) script asks grade. if enter 3(invalid input) script says input invalid , asks valid input. after if enter 4 again stops working, when supposed keep going until enter negative number make start calculating average of valid inputs.
import java.util.scanner; public class average { public static void main(string[] args){ scanner scanner = new scanner(system.in); system.out.println("the program calculate average of user inputted grades."); system.out.println("the program start calculating negative integer"); double grade; double sum = 0; int count = 0; { system.out.print("input grade (4-10): "); grade = scanner.nextdouble(); if (grade >= 4 && grade <= 10){ sum = sum + grade; count++; } } while (grade >= 4 && grade <= 10); { while (grade >= 0 && grade < 4 || grade > 10){ system.out.println("invalid grade!"); system.out.print("input grade (4-10): "); grade = scanner.nextdouble(); if (grade < 0){ system.out.println(count + " grades given."); system.out.println("average: " + sum/count); break; } } } }
it doesn't work because loops separated, if first false, second works once , stops. try this:
import java.util.scanner; public class average { public static void main(string[] args){ scanner scanner = new scanner(system.in); system.out.println("the program calculate average of user inputted grades."); system.out.println("the program start calculating negative integer"); double sum = 0; int count = 0; double grade; do{ system.out.print("input grade (4-10): "); grade = scanner.nextdouble(); if(grade >= 4 && grade <= 10){ sum = sum + grade; count++; }else{ system.out.println("invalid grade!"); } }while(grade >= 0); system.out.println(count + " grades given."); system.out.println("average: " + sum/count); } }
Comments
Post a Comment