Calculating the min and max and deleting them - java

so for my project this is what i need to do In the sport of diving, seven judges award a score between 0 and 10 where each score may be a floating-point value. The highest and lowest scores are thrown out and the remaining scores are added together. The sum is then multiplied by the degree of difficulty for that dive. The degree of difficulty ranges from 1.2 to 4.8 points. The total is then multiplied by 0.6 to determine the diver’s score.
Write a program that prompts the user for the degree of difficulty and seven judges’ scores and outputs the overall score for that dive. The program should use an array to store the seven scores. The program should also ensure that all inputs are within the allowable data ranges.
Sample output:
Enter the degree of difficulty for the dive (1.2 - 4.8): 7.3
Invalid difficulty. Please re-enter: 1.5
Enter the score for each judge (0.0 - 10.0):
Enter score for judge 1 : 12.3
Invalid score. Please re-enter: 14.5
Invalid score. Please re-enter: 8
Enter score for judge 2 : 7.5
Enter score for judge 3 : 8.5
Enter score for judge 4 : 8
Enter score for judge 5 : 7
Enter score for judge 6 : 8
Enter score for judge 7 : 7.5
Score for the dive is 35.1
What I am stuck on is how to get a code that will automatically take out the min and max...
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Random rng = new Random();
int[] values = new int[1000];
// Fill it up
for (int i = 0; i < values.length; i++) {
values[i] = rng.nextInt(100);
}
// Find min
/*int indexOfMin = 0;
int indexOfMax = 0;
for (int i = 0; i < values.length; i++) {
if(values[i] < values[indexOfMin]) {
indexOfMin = i;
}
if (values[i] > values[indexOfMax]) {
indexOfMax = i;
}
}
System.out.println("Minimum is at index " + indexOfMin + " with value " + values[indexOfMin]);
System.out.println("Maximum is at index " + indexOfMax + " with value " + values[indexOfMax]);
*/
double[] difficulty = new double[1];
Scanner keyboard = new Scanner(System.in);
for (int d = 0; d < difficulty.length; d++) {
System.out.println(" Enter Difficulty " + d + ":" );
difficulty[d] = keyboard.nextDouble();
while (difficulty[d] < 1.2 || difficulty[d] > 4.8) {
System.out.println(" Bad value. Try again: ");;
difficulty[d] = keyboard.nextDouble();
}
Scanner keyboard1 = new Scanner(System.in);
double[] scores = new double[7];
for (int i = 0; i < scores.length; i++) {
System.out.println(" Enter score " + i + ":" );
scores[i] = keyboard1.nextDouble();
while (scores[i] < 0.0 || scores[i] > 10.0) {
System.out.println(" Bad value. Try again: ");;
scores[i] = keyboard1.nextDouble();
}
}
}
}
}
and the indecOfMin and indexOfMax are // out of the code because I think i have it wrong or that it doesnt apply/help with this project

Instead of searching for the min or max, you can sort the array of values, and then pull the max off of one end of the array, and the min off of the other end.
For the sorting, you can use a bubble sort:
public double[] bubbleSort(double[] array) {
int numberOfItems = array.length;
for (int pass=1; pass != numberOfItems; pass++) {
for (int index=0; index != numberOfItems-pass; index++) {
if (array[index] < array[index+1]) {
temp = array[index];
array[index] = array[index+1];
array[index+1] = temp;
}
}
}
return array;
}
That will sort the array from least to greatest, and return it.
Then you can pull from the array like this:
int maxIndex = array.length - 1;
double max = array[maxIndex];
double min = array[0];
You may have to make some minor changes to implement it into your own code.

Related

How to display the highest and lowest numbers input by the user?

The program asks the user to input any amount of people they want. The program will then ask for the height of each person (not in feet, just in whole numbers like 5, 7, 10, etc.). The program then displays the average height of all those people as well as the tallest and shortest height out of those people.
The average height part works but my problem is trying to display the tallest height entered and shortest height entered.
package loop2;
import java.io.Reader;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.Scanner;
public class PgmTemplate {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
int sum =0;
int number=0, n;
int average = 0;
int highest= 0;
int lowest= 0;
lowest = number;
System.out.println("enter the number of people");
n = input.nextInt();
for(int i = 0; i < n; i++) {
System.out.println("enter the height of each person");
number = input.nextInt();
sum += number;
average = sum / n;
}
if(number > highest) {
highest = number;
}else if(number < lowest) {
lowest = number;
}
System.out.println("the average height is "+ average);
System.out.println("the tallest person is " + highest);
System.out.println("the shortest person is " + lowest);
}
}
No need to calculate the average after every input.
I would do it like this:
lowest = Integer.MAX_VALUE
...
for (int i = 0; i < n; i++) {
int number = scanner.nextInt();
sum += number;
if (number > highest)
highest = number;
if (number < lowest)
lowest = number;
}
Then after getting all the input, you have what you need:
System.out.println("the average height is " + (sum / n));
System.out.println("the tallest person is " + highest);
System.out.println("the shortest person is " + lowest);
You need to put those checks between number, highest and lowest inside the loop.
As it stands you're only checking for the latest number that has been input.
Also you don't need to calculate a running average. So, move that outside the loop.
for (int i = 0; i < n; i++) {
System.out.println("enter the height of each person");
number = input.nextInt();
sum += number;
if (number > highest) {
highest = number;
} else if (number < lowest) {
lowest = number;
}
}
average = sum / n;

How to sort an array and display it? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
Here is my code:
package project4;
import java.util.Scanner;
public class ScoreAnalyzer {
//#OfScores is the length of the scores array
public static int numberOfScores = 0;
public static double[] scores = new double[numberOfScores];
public static double sum = 0.0;
public static double place = 0.0;
//Of sorted list
public static double[] sortedList = new double[numberOfScores];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of scores you'd like to average: ");
numberOfScores = input.nextInt();
scores = new double[numberOfScores];
for (int count = 0; count < scores.length; count++) {
System.out.print("Enter score #" + count + ": ");
place = input.nextDouble();
scores[count] = place;
System.out.println("The score of " + scores[count] + " is " + getGrade(count));
}
sumOfScores();
System.out.println("The average of these scores is: " + averageOfScores());
sort();
System.out.println("The sorted list of scores (above average scores are "
+ "marked with an\n" + "asterisk '*'): " + sortedList[numberOfScores]);
}
public static char getGrade(int i) {
//this
if (scores[i] >= 90.0) {
return 'A';
}
if (scores[i] >= 80.0) {
return 'B';
}
if (scores[i] >= 70.0) {
return 'C';
}
if (scores[i] >= 60.0) {
return 'D';
}
else {
return 'F';
}
}
public static double sumOfScores() {
//sum = 0.0;
for (int i = 0; i < numberOfScores; i++) {
sum += scores[i];
}
return sum;
}
public static double averageOfScores() {
double average = sum / numberOfScores;
return average;
}
public static void sort() {
for (int i = 0; i < scores.length - 1; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMin = scores[i];
int currentMinIndex;
currentMinIndex = i;
for (int j = i + 1; j < scores.length; j++) {
if (currentMin > scores[j]) {
currentMin = scores[j];
currentMinIndex = j;
}
}
// Swap list[i] with list[currentMinIndex] if necessary;
if (currentMinIndex != i) {
sortedList[currentMinIndex] = scores[i];
scores[i] = currentMin;
}
}
}
}
The program's purpose is to prompt the user for the number of scores to be entered first, then allow the user to enter that number of scores. As each score is entered, the program should give them a grade for each score inputted. The program then should use a method to find the sum, pass that sum into a method that finds the average, and sort the array in a method.The sorted array should be displayed along with the average and each score which is above the average should be noted with an asterisk beside it.
When I run the program, I am able to enter the number of scores I want to average, input those scores, obtain the sum and average but I'm having problem sorting it to have the asterisk to above average numbers:
Enter the number of scores you'd like to average: 3
Enter score #0: 90
The score of 90.0 is A
Enter score #1: 80
The score of 80.0 is B
Enter score #2: 70
The score of 70.0 is C
The average of these scores is: 80.0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at project4.ScoreAnalyzer.sort(ScoreAnalyzer.java:86)
at project4.ScoreAnalyzer.main(ScoreAnalyzer.java:32)
There is a problem with the terminating condition of your for loop. Since the array index starts with 0, the highest index will go up to 2 for an array of size 3. However, count, using which you are accessing elements of scores[], is going up to 3 in your for loop and that is the reason for the ArrayOutOfBoundsException. Change the for loop as follows:
for (int count = 0; count < scores.length ; count++)

Why does my code output ridiculous numbers with the provided set? I'm trying String.format

I am using these numbers: 5,4,3.5,10,20,40,80,93.33,-1. It will work with something simple with only 5 numbers like: 5,4,3,2,1. What is going on? I am trying to use String.format to shorten the number if that is the issue. Do you guys notice anything within my code that I could do differently to maybe avoid this. This is the output with the provided set:
The minimum is -1.0, the maximum is 2.147483647E9, and the average is 2.38609322E8
-238609317.00
-238609318.00
1908874325.00
-238609312.00
-238609302.00
-238609282.00
-238609242.00
-238609229.00
-238609323.00
Desired Output
The Minimum is 3.5, The maximum is 93.33, and the average is 31.978749999999998
Score 5.0 is -26.978749999999998 from the average
Score 4.0 is -27.978749999999998 from the average
Score 3.5 is -28.478749999999998 from the average
Score 10.0 is -21.978749999999998 from the average
Score 20.0 is -11.978749999999998 from the average
Score 40.0 is 8.021250000000002 from the average
Score 80.0 is 48.02125 from the average
Score 93.33 is 61.35125 from the average
public static void main(String[] args)
{
int count = 0;
int arrayLength;
double min = 99999;
double max = 0;
double average;
double sum = 0;
JOptionPane.showMessageDialog(null, "This program will display the average as well as each numbers distance from the average");
// need to put loop here.
arrayLength = IO.readInt("How many numbers will you be entering?");
if (arrayLength <= 0 || arrayLength > 100)
{
JOptionPane.showMessageDialog(null, "Nothing entered, program will close.");
System.exit(0);
}
double[] array = new double[arrayLength];
for (int i = 0; i <arrayLength; i++)
{
array[i] = IO.readInt("Enter number: " + (i+1));
count++;
}
for (int i = 0; i <arrayLength; i++)
{
sum = (array[i] + sum);
if (array[i] <= min)
{
min = array[i];
}
if (array[i] > max)
{
max = array[i];
}
}
average = (sum / arrayLength);
System.out.println("The minimum is " + min + ", the maximum is " + max + ", and the average is " + average);
double[] array2 = new double[arrayLength];
for (int i = 0; i <arrayLength; i++)
{
array2[i] = (array[i] - average);
}
for (int i = 0; i <arrayLength; i++)
{
System.out.println(String.format("%.2f", array2[i]));
}
}
I don't know what happens when you do IO.readInt and put it into a double, but it isn't liable to be what you want...

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.

Struggling to calculate average, min and max in java

I am currently struggling to calculate the average, minimum and maximum in my coding. I am receiving a lot of errors and not sure as to what I am doing wrong. Sorry if I am not providing enough information, I will update my post if needed. Also, I would appreciate if you can explain as to why you used that code so that I can understand please. Thank you.
EDIT - What I want it to do is when the user enters a set of numbers and finished inputting numbers, I want it to display the average of the numbers the user inputted after the histogram as well as the maximum and minimum. I assumed I would have to use my count variable as well as my num variable but still struggling in implementing it.
Errors I am receiving are shown in my coding below within the lines of coding.
import java.util.Scanner;
public class Histogram1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[5000];
int num = 0;
int count = 0;
int total = 1;
int max = 0;
int min = 0;
System.out.println ("Enter students marks in the range 0 to 100\n");
loop: for (count = 0; count <= total; count++)
{
System.out.println ("Enter a number:");
num = scan.nextInt();
if (num < 0 || num > 100)
{
break loop;
}
array[count] = num;
total = count+1;
}
System.out.println ("How many times a number between 0-100 occur.");
String[] asterisk = {"0- 29 | ", "30- 39 | ","40- 69 | ", "70- 100 | "}; //4 strings
for (count = 1; count <= total; count++)
{
num=array[count];
if (num >=0 && num <=29) asterisk [0] +="*";
else if (num>29 && num <=39) asterisk[1] +="*";
else if (num>39 && num <=69) asterisk[2] +="*";
else if (num>69 && num <=100) asterisk[3] +="*";
}
for (count =0;count < 4;count++)
System.out.println(asterisk[count]);
System.out.println("The total amount of students is " + total);
**int cannot be dereferenced** for (int i = 0; i < count.length; i++) {
**array required, but int found** num += count[i];
**array required, but int found** if (min > num[i]) {
**array required, but int found** min = num[i];
}
**array required, but int found** if (max < num[i]) {
**array required, but int found** max = num[i];
}
}
**int cannot be dereferenced** double average = (double) num / count.length;
System.out.printf(" min: " + min);
System.out.printf("%n max: " + max);
System.out.printf("%naverage: %.1f", average);
}
}
If you have an array, minimum is often calculated by first setting the initial minimum value to a known maximum value "infinity" or in this case 100. Next step would be to iterate over your set of values and check whether a value is below current minimum, and if so set minimum to that value.
int min = 100;
for (int i = 0; i < total; i++) {
if (array[i] < min) {
min = array[i];
}
}
for maximum, do the other way around, setting initial maximum value to 0 or negative "infinity" and check whether a value in the array is greater than current maximum value.
for average, sum all values and divide the result on the total amount of elements in the array.
int sum = 0;
for (int i = 0; i < total; i++) {
sum += array[i];
}
double avg = (double) (sum) / total;
In java positive infinity as integer type is represented as Integer.MAX_VALUE and negative infinity: Integer.MIN_VALUE.
Let's assume we have an array of values: int[] values = { some values }
To calculate average:
loop through the array and calculate the sum
divide sum by number of elements
int sum = 0;
for(int i : values) {
sum += i;
}
double average = (double)(sum) / values.length;
To find min and max:
loop through the array and compare current element with min and max and set them appropriately
int max = -2147483648; //set to min int value, -2^31
int min = 2147483647; //set to max int value, 2^31 - 1
for (int i : values) {
if (i > max) max = i;
if (i < min) min = i;
}
I see that the other posts have already answered how to calculate average, min, and max in an array, so I will only be tackling the error with your code.
You receive an error that says that int cannot be dereferenced:
tmp.java:48: int cannot be dereferenced
for (int i = 0; i < count.length; i++) {
^
This stems from the fact that you have defined count as an int not as an array. In fact, all of the compiling errors come from here. The variable count will not have a length, nor can you access its elements (it has none). In the last part of your code (where the errors arise) you have confused count, min, and max as arrays, whereas they are actually just integers. Your code was close (had the proper idea), but I think you might have confused some of the syntax.
Because your array length is always 5000, I had to use the second for loop to calculate the minimum number. Otherwise, if I was to use the first for loop (that is now commented), the minimum number would always be 0 (if less than 5000 numbers inputted) because there would always be trailing elements that are = 0. I would suggest using an ArrayList instead, but my code for you uses the same array you created.
I commented everything I changed/added from your code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[5000];
int num = 0;
int count = 0;
int total = 0; // start this at 0, in case no inputs are valid
double sum = 0; // make this a double to get a decimal average
int max = 0; // start at the lowest possible number for max
int min = 100; // start at the highest possible number for min
double average = 0;
System.out.println ("Enter students marks in the range 0 to 100\n");
loop: for (count = 0; count <= total; count++)
{
System.out.println ("Enter a number:");
num = scan.nextInt();
if (num < 0 || num > 100 || total == 5000) // can't enter more than 5000 (array length restriction)
{
break loop;
}
array[count] = num;
sum += num; // keep track of the sum during input
total = count+1;
}
System.out.println ("How many times a number between 0-100 occur.");
String[] asterisk = {"0- 29 | ", "30- 39 | ","40- 69 | ", "70- 100 | "}; //4 strings
for (count = 1; count <= total; count++)
{
num=array[count];
if (num >=0 && num <=29) asterisk [0] +="*";
else if (num>29 && num <=39) asterisk[1] +="*";
else if (num>39 && num <=69) asterisk[2] +="*";
else if (num>69 && num <=100) asterisk[3] +="*";
}
for (count =0;count < 4;count++)
System.out.println(asterisk[count]);
System.out.println("The total amount of students is " + total);
// calculate the average
average = sum / total;
// calculate the min and max
// use this for loop if the length of the array is
// the amount of the inputs from the user
/*for (int i : array) // for every int in the array of inputted ints
{
if (i > max) max = i; // if this int in array is > the last recording max number, set the new max number to be this int
if (i < min) min = i; // if this int in array is < the last recording min number, set the new min number to be this int
}*/
for (int i = 0; i < total; i++) // for every inputted int ( < total so that you exclude the trailing elements that are = 0)
{
if (array[i] > max) max = array[i]; // if this int in array is > the last recording max number, set the new max number to be this int
if (array[i] < min) min = array[i]; // if this int in array is < the last recording min number, set the new min number to be this int
}
// my way of printing results
//System.out.println("\n Average: " + average);
//System.out.println("Max: " + max + "\n Min: " + min);
System.out.printf(" min: " + min);
System.out.printf("%n max: " + max);
System.out.printf("%naverage: %.1f", average);
}

Categories