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++;
}
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);
}
}
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];
}
So I have a sentinel value of -1 and it should kick me out of the program when I enter that value.
The problem I have is that value is included when I calculate the average and I don't want that.
Example of what happens: ( 8+ 5 + 3 + -1 / 4)
What I'd like to happen: (8 + 5 + 3 / 3)
do {
grade = Integer.parseInt(JOptionPane.showInputDialog("Enter a grade:"));
sum = sum + grade;
count = count + 1;
} while (grade != SENTINEL);
avg = sum/count;
JOptionPane.showMessageDialog(null,String.format("%.1f",avg));
You can change your logic slightly:
do {
grade = Integer.parseInt(JOptionPane.showInputDialog("Enter a grade:"));
if (grade == SENTINEL) {
break; // exit the loop upon hitting the SENTINEL value
}
sum = sum + grade; // only increase the sum for positive values
count = count + 1;
} while (true);
avg = sum/count;
JOptionPane.showMessageDialog(null,String.format("%.1f",avg));
A simple way to resolve the issue would be to wrap the 2 lines after the input in an if statement. A more proper way would be to break the loop as Tim indicated, to avoid performing the value comparison twice.
do{....
if(grade != SENTINEL)
{
sum = sum + grade;
count = count + 1;
}
}while...
The following code outputs the sum, average, count of positive/negative numbers, count of all numbers correctly when ran first time. Because it loops, hence, the output remains on the console prompting user to enter numbers again. At this time, only sum shows the correct output, other values doubles. Please help me in fixing the loop. Thanks!
public class Test {
public static void main(String[] args) {
long n;
int count=0;
float average;
int positive=0;
int negative =0;
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter a positive or negative integers: ");
n = in.nextLong();
if (n == 0){
System.out.println("Integers you've entered is invalid. Please re-launch the Program.");
}
else
{
int sum=0;
do
{
//Find sum of the integers entered.
sum += n %10;
n /= 10;
//Count number of integers entered.
count++;
//Find average of the numbers
average = sum / count;
//Find a count of positive and negative numbers.
if(n < negative){
negative++;
}
else{
positive++;
}
} while (n != 0);
n = sum;
System.out.println("The Sum of the numbers: " + sum);
System.out.println("The Average of the numbers: " + average);
System.out.println("Positive numbers are: " + positive);
System.out.println("Negative numbers are: " + negative);
System.out.println("The count of all numbers: " +count);
}
} while(n != 0);
}
}
It would make sense that sum is the only one that outputs correctly; It's the only value you initialize every iteration of your outer loop.
the values count, positive, and negative aren't re-initialized each iteration, so when you begin the next iteration of your outer loop, they will start from wherever they printed as.
you might want to initialize them again every time you run the loop.
You never reinitialize your variables before entering in your do while loop for a second time.
So
else
{
int sum=0;
do
{
Should be
else
{
int sum=0;
count=0;
average=0.0f;
positive=0;
negative =0;
do
{
So I'm trying to make a program where it averages out your golf scores. I edited a standard averaging calculator to make it work:
import java.util.Scanner;
public class Test {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int total = 0;
int score;
int average;
int counter = 0;
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
average= total/10;
System.out.println("Your average score is "+ average);
}
}
But when I enter scores, I can keep entering infinite scores and it never averages them. It just keeps expecting another score. I know it has something to do with this line:
while (counter >= 0){
but I'm not sure what to do so it works right.
You never find a way to break out of the loop:
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
will loop 2 billion times (no I'm not exaggerating) since you don't have another way to break out.
What you probably want is to change your loop condition to this:
int score = 0;
while (score >= 0){
This will break out when a negative score is entered.
Also, you have an integer division at the end. You want to make floating-point, so change the declaration to this:
double average;
and change this line to this:
average = (double)total / 10.;
You need some way to beak out of the loop. For example, entering -1:
int score = input.nextInt();
if (score < 0) { break; }
total += score;
You also seem to have a couple of errors in the calculation of the average:
Don't always divide by 10 - use the value of counter.
Use floating point arithmetic. If you need an int, you probably want to round to nearest rather than truncate.
For example:
float average = total / (float)counter;
You have to specify the counter value, the default value is 0, so the condition in the while is always true, so you will go in an infinite loop.
while (true) {
score = input.nextInt();
if (score == 0) {
break;
}
total = total + score;
counter++;
}
Now your program will realize you're done entering scores when you enter the impossible score 0.