I am using arrays for a programming project due tonight. I am able to add up all the numbers of the array, but from there I am unable to remove the maximum and minimum values from it. My attempt and the actual project description is below...
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 3.8 points. The total is then multiplied by 0.6 to determine the diver’s score.
Write a computer program that inputs a degree of difficulty and seven judges’ scores and outputs the overall score for that dive. The program should ensure that all inputs are within the allowable data ranges.
package baker;
import java.util.Scanner;
public class DiveScoreDriver {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double total = 0;
double totalFinal = 0;
double divingScores[] = new double[7];
double input;
double difficultyInput = 0;
double minimum = divingScores[0];
double maximum = divingScores[0];
for (int i = 1; i < divingScores.length + 1; i++)
{
System.out.println("Judge " + i + " please enter your score.");
input = keyboard.nextDouble();
System.out.println();
if(input < 0 || input > 10)
{
System.out.println("Invalid Score");
return;
}
else
{
total += input;
}
}
while (difficultyInput < 1.2 || difficultyInput > 3.8)
{
System.out.println("Difficulty Rating: ");
difficultyInput = keyboard.nextDouble();
}
for(int i = 0; i < divingScores.length; i++)
{
if(divingScores[i] < minimum)
minimum = divingScores[i];
if(divingScores[i] > maximum)
maximum = divingScores[i];
}
total = total - maximum - minimum;
total = total * difficultyInput;
total = total * 0.6;
System.out.printf("\nThe overall score for the dive: %.1f\n", total);
}
}
The portion in particular that I am struggling with is here:
for(int i = 0; i < divingScores.length; i++)
{
if(divingScores[i] < minimum)
minimum = divingScores[i];
if(divingScores[i] > maximum)
maximum = divingScores[i];
}
total = total - maximum - minimum;
total = total * difficultyInput;
total = total * 0.6;
The code runs and produces a correct output, but it does not seem to subtract the max and min values and the problem requests... Thanks for the help!
You have forgotten to add each judge's score to the array divingScores. You can fix this by changing the first for loop to the following:
for (int i = 0; i < divingScores.length; i++)
{
System.out.println("Judge " + (i + 1) + " please enter your score.");
input = keyboard.nextDouble();
System.out.println();
if(input < 0 || input > 10)
{
System.out.println("Invalid Score");
return;
}
else
{
total += input;
divingScores[i] = input;
}
}
You should also initialize minimum as:
minimum = 0
If you do not, every score above 0 will not be considered for the minimum.
You never set the array values in the else branch within your for loop, it should look like this:
if(input < 0 || input > 10) {
System.out.println("Invalid Score");
return;
} else {
divingScores[i] = input;
total += input;
}
Before the second loop, you can use Java 8 functional programming to get the minimum and maximum like this, which is shorter:
double minimum = Arrays.stream(divingScores).min().getAsDouble();
double maximum = Arrays.stream(divingScores).max().getAsDouble();
Alternatively, you should initialize the minimum and maximum values properly, one way to do this in general for at least one element in the array is:
double minimum = Double.MAX_VALUE; // Use your maximum in your case
double maximum = Double.MIN_VALUE; // Use your minimum in your case
You can sort the array and then add the array elements except first and last element of sorted array which will automatically remove the minimum and maximum
Arrays.sort(divingScores);
double ans=0;
for(int i=1;i<divingScores.length-1;i++){
System.out.println(divingScores[i]);
ans+=divingScores[i];
}
Related
I'm trying to get the sum, average, minimum and maximum of five numbers but somehow I get this output. I'm trying to re-code it all over again but it is still the same. Can you help me check this guys...
Here's my code:
import java.util.*;
public class Kleine {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double average;
int count = 0, sum = 0, num, min = 0, max = 0;
System.out.println("Please enter the number of numbers you wish to evaluate:");
do {
num = scan.nextInt();
sum += num;
count++;
} while (count < 5);
average = sum / 5;
{
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
System.out.println("Your average is: " + average);
System.out.println("The sum is: " + sum);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
}
}
Here's the output:
Please enter the number of numbers you wish to evaluate:
1
10
5
-3
6
Your average is3.0
The sum is:19
Your maximum number is 6
Your minimum number is 0
BUILD SUCCESSFUL (total time: 19 seconds)
The minimum and maximum numbers goes somewhere...
a little advice please...
The best way to handle the min/max values is to keep track of them as your read in each value:
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i=0; i < 5; ++i) {
num = scan.nextInt();
if (num > max) max = num;
if (num < min) min = num;
sum += num;
}
double average = sum / 5.0d;
I seed the max and min values with the smallest/largest integer values, respectively. This lets us capture the actual min and max values as they are read in. Also, I think that a basic for loop works better here than a do while loop.
Note that I compute the average using a double type, because it may not be a pure integer value (even in your sample data the average is not an integer).
Use
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
And your
{
if(num>max)
max=num;
if(num<min)
min=num;
}
needs to be inside the do-while loop, or else it runs only for the last value of number entered.
For a start you can use Math.min & Math.max. The average is sum / count.
An example getting a min number without a loop would be:
long min = Integer.MAX_VALUE;
min = Math.min(min, 9);
min = Math.min(min, 4);
min = Math.min(min, 6);
// min = 4
Do something similar for max.
You'd also be better off starting with a list or array of numbers. Get the output right, then add more complicated things like user input.
You can do it this way without defining number of integers to read:
import java.util.ArrayList;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("Next number?");
numbers.add(in.nextInt());
IntSummaryStatistics summaryStatistics = numbers.stream()
.mapToInt(Integer::valueOf)
.summaryStatistics();
System.out.println(String.format("Max: %d, Min: %d, Average: %s, Sum: %d", summaryStatistics.getMax(), summaryStatistics.getMin(), summaryStatistics.getAverage(), summaryStatistics.getSum()));
}
}
}
If I just change the existing code, the logic should be like below:
do{
num=scan.nextInt();
sum+=num;
if(count==0){
min=num;
max=num;}
if(num>max)
max=num;
if(num<min)
min=num;
count++;
}while(count<5);
average = sum/5;
The issue was that your min-max condition was outside the loop and you were initializing min and max by 0. You should set min/max to your first input number.
Min and Max were now equal to the max and min of integer. now if any number is less than min and greater than max, min and max takes their position. The average and the sum functionality was great. The problem in your code was that it was getting the max and min after the loop for input has executed. The flow was wrong.
import java.util.*;
public class Kleine {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
double average;
int count=0, sum=0, num=0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
System.out.println("Please enter the number of numbers you wish to evaluate:");
do{
if(num>max) max=num;
if(num<min) min=num;
num=scan.nextInt();
sum+=num;
count++;
}while(count<5);
average = sum/5;
System.out.println("Your average is"+average);
System.out.println("The sum is:"+sum);
System.out.printf("Your maximum number is %d\n",max);
System.out.printf("Your minimum number is %d\n",min);
}
}
System.out.print("Please enter the max number:");
int max = input.nextInt();
System.out.print("Please enter the base:");
int base = input.nextInt();
for (int i = 0; i <= max; max % base == 0;) {
System.out.println("Number is " + i);
}
How do I get it to print the multiples of a number?
Although Diabolus already has a solution, here's the same using a for loop:
for(int i = base; i <= max; i++)
{
if(i % base == 0)
System.out.println("Number is - " + i);
}
The number iterates from the base to the maximum number (if you start from zero, 0 too will be printed, as it divides completely by any number)
Note that even the base number will be printed. If you wish to avoid this, set i = base to i = base + 1.
I'm not sure if I have fully understood your question. However, I believe this is the solution you were looking for:
int currentMultiple = 0;
int step = 1;
do {
currentMultiple = (base * step);
System.out.println(currentMultiple);
step += 1;
} while ( currentMultiple <= max );
You're needing a while or do while loop for this problem. Since you are unaware of when the current multiple is going to exceed the input.
Let me know if this is what you needed!
Please help me to figure out my mistakes. When I input scores in ascending order like 4,5 the minimum is given as 100.I don't know how to change it then?
Here is my code :
float score=0,min=100,max=0,sum1=0,count=0,sum2=0;
float average,sd;
Scanner a=new Scanner(System.in);
while(score>=0)
{
System.out.println("enter the score(a negative score to quit)");
score=a.nextInt();
if(score<0)
break;
if(score>=max){
max=score;
sum1+=max;
}
else
{
min=score;
sum2+=min;
}
count++;
}
average=(sum1+sum2)/(count++ );
System.out.println("the average : " + average);
System.out.println( "the maximum score: "+ max);
System.out.println("the min score: "+ min );
I think you're overcomplicating the problem: you should try thinking about the task at hand in logical steps:
Have users input numbers
Add the next int that came in to the total score
Check if the next int is > last known maximum, if so, set the last known maximum to next int's value
Else check if the next int < last known minimum, if so, set the last known minimum to next int's value
Continue while there is more input available
Print the maximum score
Calculate and print the average score (totalScore / amountOfInputs)
Print the minimum score
That'd look like this:
import java.util.*;
public class MaxMinAverage {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double score, currentMinimum = Integer.MAX_VALUE, currentMaximum = Integer.MIN_VALUE, count;
while (in.hasNextInt()) {
int nextInt = in.nextInt();
if (nextInt < 0) { //break out of the loop
break;
} else {
score += nextInt;
count++;
if (nextInt > currentMaximum) {
currentMaximum = nextInt;
} else if (nextInt < currentMinimum) {
currentMinimum = nextInt;
}
}
}
System.out.println("Max: " + currentMaximum);
System.out.println("Avg: " + (score / count));
System.out.println("Min: " + currentMinimum);
}
}
change your else to else if (score < min) and you are getting the correct minimum.
The reason why, it checks if score if greater then the current max, if this is not the case then it simply does assume, due to the else, that score is the new min.
if (score >= max) {
max = score;
}
else if (score < min){
min = score;
}
// Just add the score value to the sum, it doesn´t matter if it´s min or max
sum2 += score;
count++;
Simplify:
while((score = a.nextInt()) >= 0) {
min = Math.min(min, score);
max = Math.max(max, score);
sum += score;
average = sum / count++;
}
when I execute this program, it prints the max value just fine, however the min value always prints to zero. I continue to scratching my head... Can anyone see what is wrong here? Thanks for looking.
import java.util.Scanner;
public class MinMax
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int [] numbers = new int[5];
int max = numbers[0];
int min = numbers[0];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Enter your next number:");
numbers[i] = kb.nextInt();
if (numbers[i] > max)
{
max = numbers[i];
}
if (min > numbers[i])
{
min = numbers[i];
}
}
System.out.println("The maximum value in your array is " + max);
System.out.println("The minimum value in your array is " + min);
}
}
The issue is that when the array is declared, the ints in the array are set to 0. Setting the min to numbers[0] would set min to 0. If that's not your min, your code will fail.
In this case, you don't need the array - you could just store whatever the user inputted. That aside, just check whether i==0 and when it does, set min and max to numbers[0]. (If you didn't do the same for max, an array of all negatives would fail.)
It's simple. The min variable is never updated because every time that min > numbers[i] is evaluated returns false. Let's to see an example:
min = 0.0 > numbers[i] = 4.5 -> false
min = 0.0 > numbers[i] = 3.8 -> false
min = 0.0 > numbers[i] = -8.9 -> true, min = -8.9
min = -8.9 > numbers[i] = 7.5 -> false
min = -8.9 < numbers[i] = 5.6 -> false
The value of min is: -8.9
With Java 8 you can get the max and min values easy with lambdas:
max = Arrays.stream(numbers).max().getAsDouble();
min = Arrays.stream(numbers).min().getAsDouble();
As other answers here are saying, the problem is that numbers[0] starts out initialized to 0, so regardless of the numbers the user enters, your code still finds 0 to be the minimum value.
What you need is an extra state to represent "I don't have any minimum value yet". You could use an extra boolean variable to represent this tate, or if you can use the Integer wrapper type, you can use null.
For example:
Integer minimum = null;
Integer maximum = null;
for (int i = 0; i < 5; i++) {
int number = kb.nextInt();
if (minimum == null || number < minimum) {
minimum = number;
}
if (maximum == null || number > maximum) {
maximum = number;
}
}
System.out.println("minimum: " + minimum);
System.out.println("maximum: " + maximum);
I am writing a program where I must ask the user how many assignments they have. Then, I must ask them for their score and the maximum points possible for the assignment. I know how to find the sum of the first set of numbers they entered (their scores) but I am stuck on how I would go about totaling the maximum points possible. Here is what I have so far:
int totalNumber = scan.nextInt();
double sum = 0.0;
for (int i = 1; i <= totalNumber; i++) {
System.out.print("Assignment " + i + " score and max? ");
double score = scan.nextDouble();
double maxScore = scan.nextDouble();
sum += score;
The output looks something like this:
Assignment 1 score and max? 16 17
Assignment 2 score and max? 18 19
I am not sure how I would total the maximum points (17 and 19 in the example) because I must print the total points:
(sum of scores)/(sum of maximum points).
Thanks.
the simple answer is to add another variable for summing the maxScore
int totalNumber = scan.nextInt();
double sum = 0.0;
double maxSum = 0.0;
for (int i = 1; i <= totalNumber; i++) {
System.out.print("Assignment " + i + " score and max? ");
double score = scan.nextDouble();
double maxScore = scan.nextDouble();
sum += score;
maxSum += maxScore;
}