Min and Max Values [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have to make code to find the max, min, and average of grades. This is what I have so far:
public class test
{
public static void main (String[] args)
{
double average, count = 0, sum = 0, grades, max=0, min=0;
final int = MAX_GRA = 0
final int = MIN_GRA = 0
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the grades (999 to quit): "); //Taking input from the user
grades = scan.nextInt();
while (grades != 999) //A while loop that doubles count and adds the sum to grades
{
count++;
sum += grades;
System.out.println ("The sum so far is " + sum);
System.out.print ("Enter the grades (999 to quit): ");
grades = scan.nextInt();
}
System.out.println ();
if (count == 0) //An if statement that identifies if no numbers were entered
System.out.println ("No grades were entered.");
else //An else statement that computes that computes the average
{
average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat ("0.##");
System.out.println ("The average grade is " + fmt.format(average));
}
}
}
Any ideas? I'm new to java and coding in general. Thank you for your time!

You could try something like this:
int maxGrade = 0;
int minGrade = 10; // Set the highest possible grade.
while (grades != 999)
{
// If the current grade is greater that the maxGrade,
// set this value the maxGrade.
if(grades > maxGrade)
maxGrade = grades;
// If the current grade is less than the minGrade,
// set this value to the minGrade.
if(grades < minGrade)
minGrade = grades;
// Here you will place the rest of your code.
}
Note: Try to use more meaningful names for your variables. This will make your code more readable and it convey far easier your intentions and thoughts to the reader of your code. For instance, since grades would keep the value of the current grade, it would be more reasonable to name it as grade.
Update
As correctly laune mentioned below you could make use of two methods of Math class, in order to avoid the if statements.
while (grades != 999)
{
maxGrade = Math.max(maxGrade, grades);
minGrade = Math.min(minGrade, grades);
}

I would change somethings in the original code, and put like this.
public class Grades {
// MODIFIERS (final, private, protected, static, etc.) type (int, double,
// float, Object, etc.) name [= initialValue];
private final static double END_GRADES = 999;
public static void main(String[] args) {
double count, sum, grades, max, min;
Scanner scan = new Scanner(System.in);
// Initialized data.
count = 0;
sum = 0;
max = 0;
min = 0;
do {
System.out.println("Enter next grade ("+(int)END_GRADES+" to quit):");
grades = scan.nextDouble();
if (grades != END_GRADES) {
if (count == 0) { // First grade is always min.
min = grades;
}
sum = sum + grades;
count++;
System.out.println("The sum so far is: " + sum);
if (max < grades) { // New max??
max = grades;
}
if (min > grades) { // New min??
min = grades;
}
}
} while (grades != END_GRADES);
if (count != 0) {
System.out.println("The average grade is: " + (sum / count));
System.out.println("The max grade is: " + max);
System.out.println("The min grade is: " + min);
} else {
System.out.println("No grades were entered.");
}
}
}

Look like you took half the way to the answer, but I assume you are missing the min,max values as you average and sum are already computed.
First you need to add two instruction to update your maximum and minimum variables grade holders and the short way to do is to use:
Math#max shorthand comparison returning the max of arguments.
Math#min shorthand comparison returning the min of arguments.
But you have to remove the final modifier in front of the MAX_GRA and MIN_GRA because those instance variables need to be update at each iteration in your while loop so that they get either the user entered grade or keep their own value.
You should then take care of variables declaration, so that comparisons will take place and to do so, you can set the min value to the maximum possible one in the integer range and vice vers ça.
Last you need to add print statement simply to show you max / min value along with your average of grades:
public class MinMaxAndAverageCalculator
{
public static void main (String[] args)
{
double average, count = 0, sum = 0, max=0, min=0;
int MAX_GRA = Integer.MIN_VALUE;
int MIN_GRA = Integer.MAX_VALUE;
int grade;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the grades (999 to quit): "); //Taking input from the user
grade = scan.nextInt();
while (grade != 999) //A while loop that doubles count and adds the sum to grades
{
count++;
sum += grade;
MAX_GRA = Math.max(grade, MAX_GRA);
MIN_GRA = Math.min(grade, MIN_GRA);
System.out.println ("The sum so far is " + sum);
System.out.print ("Enter the grades (999 to quit): ");
grade = scan.nextInt();
}
if (count == 0) //An if statement that identifies if no numbers were entered
{
System.out.println("No grades were entered.");
}
else //An else statement that computes that computes the average
{
average = (double) sum / count;
DecimalFormat fmt = new DecimalFormat ("0.##");
System.out.println ("The average grade is " + fmt.format(average));
System.out.println ("The maximum grade is " + MAX_GRA);
System.out.println ("The minimum grade is " + MIN_GRA);
}
}
}

Related

Is there a way to have a System.out.print print something different once in a loop?

I'm very new to coding, and one of my projects was to create a program that uses a while loop to ask a user for test grades and find the average. The problem I have is that when it asks for the first grade, my instructor wants it to also print out "Enter -1 when you're finished" along with the first grade only. He wants the results to look something like this.
Test grade1? (Enter -1 when you are finished): random grade
Test grade2? random grade
Test Grade3? random grade
The average of your test grades is: average of all grades
Currently, I have the first grade as a separate line of code that asks the user and it is not in the loop. Is there any way to combine it into the loop and still have it to ask "Enter -1 when you're finished" but for only the first test grade?
P.s Sorry if my code is very messy I'm still not very good at it.
import java.util.Scanner;
public class U4D3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Test grade 1? (Enter -1 when you're finished): ");
int grade1 = scan.nextInt();
int i = 2;
int testCounter = 1;
int sum = 0;
boolean flag = true;
while(flag) {
System.out.print("Test grade " + i + "? ");
int grades = scan.nextInt();
if (grades == -1){
flag = false;
break;
}
sum = grade1 + grades;
grade1 = sum;
i++;
testCounter++;
}
System.out.println("The averages of your test grades is: " + (double)sum/testCounter);
}
}
You can just check with an if statement whether it's the first test and display the additional message if that's the case.
Also you can get rid of the i variable and use testCounter in it's place. You also don't need the flag, just using break is enough.
At the end of the loop the testCounter will be off by one so you have to decrement by one when calculating the average ((testCounter - 1)).
import java.util.Scanner;
public class U4D3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int testCounter = 1;
int sum = 0;
while (true) {
System.out.print("Test grade " + testCounter + "? ");
if (testCounter == 1)
System.out.print("(Enter -1 when you're finished): ");
int grade = scan.nextInt();
if (grade == -1) {
break;
}
sum += grade;
testCounter++;
}
System.out.println("The averages of your test grades is: " + (double) sum / (testCounter - 1));
}
}

Need to display the Max and Min Grade from a list of numbers

I need to input a list of grades and have the code stop when I input a character. It would then display the maximum grade and the minimum grade.
I created a while loop, but when I run the code, it keeps looping and won't stop.
public class MaxMinGrades{
public static void main(String[] args){
double maxGrade = Double.MAX_VALUE;
double minGrade = Double.MIN_VALUE;
Scanner input = new Scanner(System.in);
System.out.println("Enter as many student grades as you like. Enter a character to stop.");
double grades = input.nextDouble();
while(input.hasNextDouble()) {
if (grades > maxGrade) {
maxGrade = grades;
}
if (grades < minGrade) {
minGrade = grades;
}
}
System.out.println("The highest grade is: " + maxGrade);
System.out.println("The lowest grade is: " + minGrade);
}
}
I would input: 50 66.85 73.5 78.9 77 q.
The output would be: The highest grade is: 78.9
The lowest grade is: 50.0
public class MaxMinGrades{
public static void main(String[] args){
double maxGrade = 0.0;
double minGrade = 100.0;
Scanner input = new Scanner(System.in);
System.out.println("Enter as many student grades as you like. Enter a character to stop.");
while(input.hasNextDouble()) {
double grades = input.nextDouble();
if (grades > maxGrade) {
maxGrade = grades;
}
if (minGrade > grades) {
minGrade = grades;
}
}
System.out.println("The highest grade is: " + maxGrade);
System.out.println("The lowest grade is: " + minGrade);
}
}
With this there is break condition inside of the while loop. When something changes the boolean condition is checked.
There is no break condition in the while loop.
The scanner will continue listening for input.
The loop will only exit if a non-double character is entered.
You are also not actually getting the next input on each iteration. You need to call input.nextDouble() inside the loop.
If you want it to exit on its own, you need to add a breaking condition.
For example, you could stop after a certain number of inputs like:
int gradeCount = 0;
while(input.hasNextDouble() && gradeCount < 6) {
grades = input.nextDouble();
gradeCount += 1;
// your logic here
}
Couple of points
1 . As soon as you get first entry you need to assign Min and Max with that value.
2 . variable grades should be updated with latest input inside the loop.
public class MaxMinGrades {
public static void main(String[] args){
double maxGrade = Double.MAX_VALUE;
double minGrade = Double.MIN_VALUE;
Scanner input = new Scanner(System.in);
System.out.println("Enter as many student grades as you like. Enter a character to stop.");
double grades = input.nextDouble();
System.out.println("first entry="+grades);
minGrade = maxGrade = grades;
while(input.hasNextDouble()) {
grades = input.nextDouble();
if (grades > maxGrade) {
maxGrade = grades;
}
if (grades < minGrade) {
minGrade = grades;
}
}
System.out.println("The highest grade is: " + maxGrade);
System.out.println("The lowest grade is: " + minGrade);
}
}

Some problems with my array

my lecturer give me these question:
1. Write a program that does the following:
a. Get the number of students from user (n)
b. Ask user to enter n grades of n students, store them in an array.
c. Print out the max, the min, and the average of those n grades.
Note: write 3 methods to return the max/min/average element of an array
and use them in this program.
I try to do it, but the output of my program doesn't like what I'd expected.
Here is my code:
package javaapplication2;
import java.util.*;
public class JavaApplication2 {
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i;
}
}
return max;
}
public static double min(double[]y) {
double min = max(y);
for (int i =0; i < y.length; i++) {
if (y[i] < min) {
min = y[i];
}
}return min;
}
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
double grades [] = new double [5000];
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
}
And here is my output:
Enter student's name:
k
Enter student's score:30
The max grade is: 0.0
The min grades is: 0.0
Enter student's name:
Yah, I dont know why my max grade and min grade is 0.0. Anyone, please help me, thank you !!!
Your problem comes from the grade array s being reassigned each loop
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
//you set the grades array each loop to a new empty array
double grades [] = new double [5000]; //<--- Move this one out
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
Move it out and then try to get the methods done :)
Edit:
You also have a little error in the max method in regard of the value.
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i; //<-- Not max = i but max = x[i] :)
}
}
return max;
}
In the function where you are calculating max, you should use:
if (max < x[i]) {
max = x[i];
}
As you want to return the element and not it's index. Also you would want to declare your array named grades before the while loop or else it would create a new array on every iteration.
And for improving the code performance:
1. you can in your max/min functions, exit the loop as soon as you encounter a value=0. In your current code the loop iterates 5000 times even if there is a single entry.
2. in your min function instead of doing double min = max(y); you should use double min = Double.MAX_VALUE;. It will prevent the unnecessary calling of the max function.

Java average program with any number of inputs

What I'm trying to make is an averaging program that takes any number of inputs. So far I need to have the user specify how many numbers they want to average, and if they don't give that many numbers the program crashes. Is there any way that I could just have them put as many numbers as they want and afterwards the array length is set?
Here is the code I am using right now:
import java.util.*;
public class Average_any
{
public static void main (String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println ("How many numbers do you want to enter?");
final int ARRAY_LENGTH = scan.nextInt();
System.out.println ("Please type the numbers you want to find the average of, "
+ "and then type \"Done\".");
System.out.println ("Warning: Only type the exact amount of numbers that you specified.");
// If user doesn't enter same number, results in crash
double[] numbers = new double [ARRAY_LENGTH];
do {
for (int i = 0; i < numbers.length; i++) {
while (!scan.hasNextInt()) {
System.out.println("That's not a number!");
scan.next(); //Need this to enter another input
}
numbers[i] = scan.nextInt();
}
} while (!scan.hasNext("Done"));
double total = 0;
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
}
double average = total/ARRAY_LENGTH;
System.out.println ("Your average is: " + average);
}
}
(Just in case anyone is wondering, no this is not a school assignment, I was just wondering because we did a simpler version in school)
Take the array out of the equation altogether
Scanner scan = new Scanner (System.in);
double total = 0;
int count = 0;
while (scan.hasNextDouble()) {
total += scan.nextDouble();
count ++;
}
double average = total / count;

Java program will not recognize sentinel value

My program accept input data from a user (up to 20 values) and calculate the average/find the distance from the average. If the user enters "9999" when no numbers have been added yet it will display an error message and tell the user to re-enter a value. Otherwise entering "9999" will collect what the user has entered and do its calculations. My program will have to collect all 20 inputs from the user and also ignore when the value "9999" is entered completely but, it will do the other calculations correctly. I'm not sure why its not recognizing my sentinel value whatsoever.
package labpack;
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers = new double[20];
double sum = 0;
int sentValue = 9999;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the numbers you want up to 20");
do {
for (i = 0; i < numbers.length; i++) {
if (numbers[0] == sentValue){
System.out.println("Error: Please enter a number");
break;
}
else {
numbers[i] = input.nextDouble();
sum += numbers[i];
}
}
while (i<numbers.length && numbers[i]!=sentValue); //part of do-while loop
//calculate average and distance from average
double average = (sum / i);
System.out.println("This is your average:" + average);
for (i = 0; i < numbers.length; i++) { //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}
}
}
You can do this without doing the do-while and doing while instead.
if (numbers[0]== sentValue){
System.out.println("Error: Please enter a number");
break;
Here you are trying to compare the value without initializing the array with the user input.
This can be done in a much simple way :
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers =new double[10];
double sum =0;
double sentValue=9999;
int count = 0;
System.out.println(numbers.length);
System.out.print("Enter the numbers you want up to 20");
Scanner input = new Scanner(System.in);
while (i<numbers.length){
double temp = input.nextDouble();
if (temp >= sentValue){
if(i==0){
System.out.println("Error Message Here");
} else {
break;
}
}//if
else {
numbers[i] = temp;
sum += numbers[i];
i++;
count++;
}
} //part of while loop*/
//calculate average and distance from average
double average=(sum/i);
System.out.println("This is your average:" + average);
for (i=0;i < count;i++){ //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}//for loop
}//main bracket
}//class lab4 bracket
You need to store the value of the input.nextDouble() into a variable because when the compiler reads input.nextDouble(), each time it will ask the user for an input.
PS. You dont need to re-initialize this part :
java.util.Scanner input = new java.util.Scanner(System.in);
The above line can simply be written as :
Scanner input = new Scanner(System.in);
because you already imported Scanner.
import java.util.Scanner;
Hope this helps :)

Categories