Math.max(), Math.min() methods?
843789May 19 2009 — edited May 21 2009I am using the Math class and using the max() & min() methods to display the max and min values of scores input by the Scanner(System.in).
When I run the applicatioin a series of scores are enter unless score is 999. I use a while() and throw in an if to increment the counter.
Though when I try to end the application with 999, instead of getting the display off my calculations( avg score, total score, min & max scores), I need
to type another 4 scores before I get the display. The avg socore and total score uses the first set of scores and the min and max score uses the last
four scores. My best best is that I misplace the Math.max() and Math.min.
This is what it looks like.
I need to be able to get the min and max scores from the sc.nextInt() and then get next sc.netInt() until score is 999
I know how to get the max and min values from 2 variables
Ie
int x = 67;
int y =23;
int max = Math.max(x,y);
int min= Math.min(x,y);
But how do I get the min and max values when I am using the Scanner(Sys.in) for a different number of scores until 999 is use to exit
Hope my question make sense. Any help would be appreciated. Thank you.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bdtestscoreapp;
import java.util.Scanner;
import java.text.NumberFormat;
public class BDTestScoreApp
{
public static void main(String[] args)
{
// display operational messages
System.out.println("Please enter test scores that range from 0 to 100.");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
// initialize variables and create a Scanner object
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
while (testScore != 999)
{
// get the input from the user
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount +=1;
scoreTotal += testScore;
}
}
// converting primitive type to a String
// keep track of min and max test scores
int max=Math.max(sc.nextInt(), sc.nextInt()); *// fix arguments**
int min=Math.min(sc.nextInt(),sc.nextInt()); // arguments are giving the error.
// display the score count, score total, and average score
double averageScore = scoreTotal / scoreCount;
NumberFormat number=NumberFormat.getCurrencyInstance();
number.setMaximumFractionDigits(1);
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + number.format(averageScore) + "\n"
+ "Maximum score: "+ max +"\n"
+ "Minumum score: "+ min +"\n";
System.out.println(message);
}
}