How to print proper minimum and maximum from user input - java

I am trying to write a program that allows a user to enter in a number of random grades they want to display along with the sum, average, minimum and maximum of the generated list. The grades range from 60 - 100.
The program is printing the min properly and the sum is adding up the previously generated sum along with the newly generated one. How can I change it so that it give the correct output for the minimum and so that is stops adding the previou sum to the new one? Any help would be appreciated.
The image link for the output shows the minimum output issue. The min should be 66.0 but it says 59.0.
output
import java.util.Scanner;
public class A03C
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How many scores? ");
int howMany = input.nextInt();
double score = 0;
double sum = 0;
double average = 0;
double max = 0;
double min = 60;
while (howMany > 0)
{
for (int i = 1; i <= howMany; i++)
{
score = 60 + (int)(Math.random() * ((100 - 60) +1));
if (letterGrade(score));
sum += score++;
average = (sum/howMany);
if (score > max)
max = score;
if (score < max)
min = score;
}
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
System.out.println("Max: " + (max - 1));
System.out.println("Min: " + (min - 1));
System.out.println("How many scores? ");
howMany = input.nextInt();
}
}
public static boolean letterGrade(double score)
{
if (score >= 92.0)
System.out.println(score + " is an A");
else if (score >= 83.0)
System.out.println(score + " is a B");
else if (score >= 75.0)
System.out.println(score + " is a C");
else
System.out.println(score + " is an F");
return false;
}
}

Just clean the sum variable after the execution, also I changed the return of the letterGrade to true:
import java.util.Scanner;
public class A03C {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many scores? ");
int howMany = input.nextInt();
double score = 0;
double sum = 0;
double average = 0;
double max = 0;
double min = 60;
while (howMany > 0) {
for (int i = 1; i <= howMany; i++) {
score = 60 + (int) (Math.random() * ((100 - 60) + 1));
if (letterGrade(score))
sum += score++;
average = (sum / howMany);
if (score > max)
max = score;
if (score < max)
min = score;
}
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
System.out.println("Max: " + (max - 1));
System.out.println("Min: " + (min - 1));
System.out.println("How many scores? ");
sum = 0;
howMany = input.nextInt();
}
}
public static boolean letterGrade(double score) {
if (score >= 92.0)
System.out.println(score + " is an A");
else if (score >= 83.0)
System.out.println(score + " is a B");
else if (score >= 75.0)
System.out.println(score + " is a C");
else
System.out.println(score + " is an F");
return true;
}
}

Before continue, i definitely think that you should read #joe C comment.
As i understand you are a beginner, i will explain the changes i did.
import java.util.Scanner;
public class A03C
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How many scores? ");
int howMany = = input.nextInt();
double score = 0;
double sum = 0;
double average = 0;
double max = 60;
double min = 100;
while (howMany > 0)
{
for (int i = 1; i <= howMany; i++)
{
score = 60 + (int)(Math.random() * ((100 - 60) +1));
letterGrade(score);
sum += score++;
average = (sum/howMany);
if (score > max)
max = score;
if (score < min)
min = score;
}
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
System.out.println("Max: " + (max - 1));
System.out.println("Min: " + (min - 1));
System.out.println("How many scores? ");
howMany = input.nextInt();
}
}
public static void letterGrade(double score)
{
if (score >= 92.0)
System.out.println(score + " is an A");
else if (score >= 83.0)
System.out.println(score + " is a B");
else if (score >= 75.0)
System.out.println(score + " is a C");
else
System.out.println(score + " is an F");
}
}
Starting with the function letterGrade. Since the function always return false and just prints a sentence, you can replace boolean to void.
Another mistake you did was that if you want to find max and min, the variables shall take the inverse of you want. So the variable max shall take the minimum variable (60) and the maximum value (100).
Finally, in order to change variables max and min you must compare the new value to their current value. This is, to change min value, for example, you have to compare score with current min.
Hope it helps.

Related

How to understand why this does not return the minimum value?

Please help to understand why, in the following, I didn't get output of minimum value in array. Using scanner for input value, the program should output also the minimum number.
** without using .sort.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list;
list = new int[10000];
int sum = 0;
double avr = 0;
int min = list [0];
int max = list [0];
int x = 0;
int value;
Scanner input = new Scanner(System.in);
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
while (x <= list.length && (value != -1 || x == 0)) {
list[x] = value;
x++;
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
}
for (int i = 0; i < list.length; i++) {
sum += list[i];
avr = sum / x;
if(list[i] > max)
max = list[i];
if( list[i] < min )
min = list[i];
}
System.out.println("The sum of all values are: " + sum);
System.out.println("The average value of the numbers are: " + avr);
System.out.println("The maximum value of the numbers are: " + max);
System.out.println("The minimum value of the numbers are: " + min);
}
}
I will suggest two improvements at the bare minimum.
Initialize your min to the first value. Right now you have min initialized to 0 and user never enters any number smaller than 0. That's why you keep getting 0 for min.
Don't run your loops 1000 times. Run it as many times as there are non zero elements.
See the following working snippet:
int[] list;
list = new int[10000];
int sum = 0;
double avr = 0;
int min = list [0];
int max = list [0];
int x = 0;
int value;
Scanner input = new Scanner(System.in);
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
min = value;
while (x <= list.length && (value != -1 || x == 0)) {
list[x] = value;
x++;
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
}
for (int i = 0; i < list.length && list[i] !=0; i++) {
sum += list[i];
avr = sum / x;
if(list[i] > max)
max = list[i];
if( list[i] < min )
min = list[i];
}
System.out.println("The sum of all values are: " + sum);
System.out.println("The average value of the numbers are: " + avr);
System.out.println("The maximum value of the numbers are: " + max);
System.out.println("The minimum value of the numbers are: " + min);

Java-Number of scores needs to be one less in answer

So here is my code:
package e7;
import java.util.Scanner;
public class Q1 {
public static void main(String[] args)
{
double[] scores = new double[10];
double sum = 0.0D;
int count = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a new score (-1 to end): ");
scores[count] = sc.nextDouble();
if (scores[count] >= 0.0D)
sum += scores[count];
}
while (scores[(count++)] >= 0.0D);
System.out.println("The total number of scores is: " + count );
double average = sum / (count - 1);
int numOfAbove = 0;
int numOfBelow = 0;
for (int i = 0; i < count - 1; i++) {
if (scores[i] >= average)
numOfAbove++;
else
numOfBelow++;
}
System.out.printf("Average is " + "%.2f\n",average);
System.out.println("Number of scores above or equal to the average " + numOfAbove);
System.out.println("Number of scores below the average " + numOfBelow);
}
}
How do make it display the correct number of scores calculated? If I input 2 numbers and then do the -1 one to end it keeps saying 3 scores. Should only be two. How do I fix this? Thanks
System.out.println("The total number of scores is: " + count );
You probably want:
System.out.println("The total number of scores is: " + (count - 1));
You could also change your loop from a do while to a while loop as follows,
while (true) {
System.out.print("Enter a new score (-1 to end): ");
double tempDouble = sc.nextDouble();
if (tempDouble >= 0.0D)
scores[count] = tempDouble;
sum += scores[count];
count++;
else
break;
}
That way as if your double input isn't correct it would break out of the while loop when the user entered -1. You might have to tweak it a bit for your use case.

Java Scanner input into int and string arrays

If someone would be kind enough to give me a hand with this program it would be appreciated, it accepts multiple students names and grades using a Scanner and then puts them into 2 arrays, Students and Scores. Then it will print out like the following...
Max. Grade = 98 (Lauren)
Min. Grade = 50 (Joe)
Avg. Grade = 83.9
/* Chris Brocato
* 10-27-15
* This program will read the students names and scores using a Scanner and use two arrays to
* show the grade and name of the highest and lowest scoring student as well as the average grade.*/
import java.util.*;
public class StudentCenter {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter the number of students: ");
int students = console.nextInt();
String[] name = new String[students];
int[] scores = new int[students];
int min = 0; int max = 0; int sum = 0;
for (int i = 0; i < name.length; i++) {
System.out.print("Please enter student's name: ");
name[i] = console.next();
System.out.print("Now enter their score: ");
scores[i] = console.nextInt();
if (i == 0) {
min = students;
max = students;
}else {
if (students < min) min = students;
if (students > max) max = students;
}sum += students;
}
System.out.println("Min. Grade = " + min + name );
System.out.println("Max. Grade = " + max + name);
System.out.println("Average Grade = " + sum);
double avg = (double) sum / (double) students;
System.out.println("Avg = " + avg);
console.close();
}
}
You're setting min,max, and sum to the value of students, which is the number of students—not their scores. You should probably be setting them to scores[i].
if (i == 0) {
min = scores[i];
max = scores[i];
}else {
if (students < min) min = scores[i];
if (students > max) max = scores[i];
}
sum += scores[i];
I would also store the indices for minimum and maximum scores, so that you can reference their names later.
min = scores[i];
minIndex = i;
...
System.out.println("Min. Grade = " + min + name[minIndex] );
I would use the Min and Max values for constants.
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int maxValue = 0;
int minValue = 0;
String minName;
String maxName;
//then use them for comparison in the loop
if(scores[i] < min)
{
minValue = scores[i];
minName = name[i];
}
if(scores[i] > max)
{
maxValue = scores[i];
maxName = name[i];
}
That will store your max/min values with the associated name.
You are comparing min and max with incorrect values. students is the number of students you have not the grades. Also when printing tha names you are printing the whole array and not just a specific value. So my advice is that you create two variables like this:
int minInd = 0;
int maxInd = 0;
then change your if like this:
if (i == 0) {
min = scores[i];
max = scores[i];
} else {
if (scores[i] < min) {
min = scores[i];
minInd = i;
}
if (scores[i] > max) {
max = scores[i];
maxInd = i;
}
}
sum += scores[i];
And print the result like this:
System.out.println("Min. Grade = " + min + " ("+ name[minInd]+")");
System.out.println("Max. Grade = " + max + " ("+name[maxInd]+")");

Passing array through average method, resulting in low percent

For some reason the average is being populated wrong when I pass the array to the method I get a really low percent. It almost seems like since the Array shotsMade is only recording integers for made shots and not misses it is not calculating off the right base.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myGameCounter = 1;
int shotCount = 0;
int shotCount1 = 0;
int [] shotsMade = new int [5];
int sum = 0;
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
//Game #1
System.out.println("Game " + myGameCounter + ":");
Random r = new Random();
myGameCounter++;
shotCount = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount + " out of 10");
shotsMade[0]= shotCount;
//Game #2
System.out.println("");
System.out.println("Game" + myGameCounter + ":");
myGameCounter++;
shotCount1 = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount1++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount1 + " out of 10");
shotsMade[1]= shotCount1;
System.out.println("");
System.out.println("Summary:");
System.out.println("Best game: " + max(shotsMade));
System.out.println("Total Free Throws Made: " + sum(shotsMade) + " " + "out of 20");
System.out.println("Average Free Throw Percentage: " + average(shotsMade) +"%");
}//main
public static boolean tryFreeThrow(int percent) {
Random r = new Random();
int number = r.nextInt(100);
if (number > percent){
return false;
}
return true;
}
public static float average(int nums[]) {
int total = 0;
for (int i=0; i<nums.length; i++) {
total = total + nums[i];
}
float f = (total / nums.length);
return (float)total /(float)nums.length;
}
public static int sum(int nums[]) {
int sum = 0;
for (int i=0; i<nums.length; ++i) {
sum += nums[i];
}
return (int)sum;
}
public static int max(int nums[]) {
int max=nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
return max;
}
}//class
You are calculating the avarage of 5 numbers but you only set 2. So if all shots hit your array will look like this: 10, 10, 0, 0, 0 and the avarage will be 4.
Old issue, you are using integer arithmetic total / nums.length with returns you an int value. You later assign it to a float, but the value already has been truncated.
Just change one of the values to float before the division, v.g. ((float) total) / num
Among others, your expression
float f = (total / nums.length);
will yield an inaccurate result.
Both total and nums.length are integers, and any operation between integers always results in an integer.
Example: if total=10 and nums.length=3, you'd expect the result to be 3.333... but actually the result is just 3. Only after that do you cast it to a float, resulting in 3.0.
To get the required result, you need to cast both integers to floats before dividing:
float f = (float) total / (float) nums.length;

How to return person with max sales in salesperson program- JAVA [PT. 2]

Sorry if I'm being bothersome. But I am stuck on another part of my HW problem. I am now tasked at instead of having an salesperson 0, salespersons start with 1. I have tried to solve this by parsing the strings i to an integer and adding 1. Seemed like it would work. However, for some reason the calculating of min is not correct. It stays at 0. I've tried stepping through the code and seeing why, but I cannot see it.
import java.util.Scanner;
public class Cray {
public static void main(String[] args){
final int SALESPEOPLE = 5;
int[] sales = new int[SALESPEOPLE];
int sum, randomValue, numGreater = 0;
int max = sales[0];
int min = sales[0];
int maxperson = 0;
int minperson = 0;
Scanner scan = new Scanner(System.in);
for (int i=0; i<sales.length; i++)
{
//To attempt print out the information of salesperson 0 and salesperson 1, I returned the integer value of i and added one.
System.out.print("Enter sales for salesperson " + Integer.valueOf(i+1) + ": ");
sales[i] = scan.nextInt();
//max if statemnent works fine and is correct
if(sales[i] > max){
max= sales[i];
maxperson = i;
}
//For some reason max is calculating but not min.
if(sales[i] < min){
min = sales [i];
minperson= i;
}
}
System.out.println("\nSalesperson Sales");
System.out.println("--------------------");
sum = 0;
for (int i=0; i<sales.length; i++)
{
System.out.println(" " + Integer.valueOf(i+1) + " " + sales[i]);
sum += sales[i];
}
System.out.println("\nTotal sales: " + sum);
System.out.println("Average sales: " + sum/5);
System.out.println();
System.out.println("Salesperson " + Integer.valueOf(maxperson+1) + " had the most sales with " + max );
System.out.println("Salesperson " + Integer.valueOf(minperson+1) + " had the least sales with " + min);
System.out.println();
System.out.println("Enter any value to compare to the sales team: ");
randomValue = scan.nextInt();
System.out.println();
for(int r=0; r < sales.length; r++){
if(sales[r] > randomValue){
numGreater++;
System.out.println("Salesperson " + Integer.valueOf(r+1) + " exceeded that amount with " + sales[r]);
}
}
System.out.println();
System.out.println("In total, " + numGreater + " people exceeded that value");
}
}
The problem is that the min is never set as all positive sales will be > 0
You should initialise min as a large value so that a positive sales figure can be less then the minimum value specified in your if statement:
if (sales[i] < min) {
You could use:
int min = Integer.MAX_VALUE;

Categories