java - Storing input from a while loop outside the loop -
java - Storing input from a while loop outside the loop -
so have question wants user input unknown amount of numbers compute total , average of these numbers. wants utilize while loop inquire input of numbers based off of how many numbers user said had input. how store input utilize compute total , average?
this have:
int numofmarks, mark ; scanner kdb = new scanner(system.in); system.out.print("enter number of marks: "); numofmarks = kbd.nextint() ; int = 1 ; while(i<=numofmarks) { system.out.print("enter mark: ") ; mark = kbd.nextint() ; i=i+1 ; }
but is, mark overwritten every time loop performed. how store each loops input farther use?
for total , average, need maintain 2 variables around - 1 total, , 1 number of numbers. have - numofmarks
.
so define:
double total = 0;
inside loop, add together each mark total.
total += mark;
then @ end, can print:
system.out.println( "total: " + total ); system.out.println( "average: " + ( total / numofmarks ) );
the reason i'm using double average not whole number. utilize long (or int cases) if want average round.
java while-loop
Comments
Post a Comment