Calculating a Minimum and Maximum in Java? -
the first part of exercise calculate test score average. next problem asked me build off problem , calculate minimum , maximum. can me? code far.
import java.util.scanner; import java.io.*; import java.text.decimalformat; public class hw { public static void main ( string[] args ) { int maxgrade; int mingrade; int count=0; int total=0; final int sentinel = -1; int score; scanner scan = new scanner( system.in); system.out.println( "to calculate class average, enter each test score."); system.out.println( "when finished, enter -1."); system.out.print( "enter first test score > "); score = scan.nextint(); while (score != sentinel ) { total += score; count ++; system.out.print("enter next test score > "); score = scan.nextint(); } if (count != 0) { decimalformat onedecimalplace = new decimalformat("0.0"); system.out.println( "\nthe class average " + onedecimalplace.format( (double) (total) / count )); } else system.out.println("\nno grades entered"); } }
in while
loop, can compare current score maximum , minimum.
while (score != sentinel ) { total += score; count ++; if(score > maxgrade) maxgrade = score; if(score < mingrade) mingrade = score; system.out.print("enter next test score > "); score = scan.nextint(); }
you need set max , min (when declaring them) "opposite" value:
int maxgrade = integer.min_value; int mingrade = integer.max_value;
Comments
Post a Comment