Calculating Average with Sentinel Value - java

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...

Related

Using a return value from a method in another method

I'm trying to use the return value "average" in calcAverage method into the determineGrade method to get out a char value (A B C D F).
However, it repeats the loop when I code this way. Is there a way to just get the return value from the calcAverage and not have to execute the loop again and ask the same test scores?
package Chapter5;
import java.util.Scanner;
public class TestAverageAndGradewithLoop {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("How many tests?: ");
int test = input.nextInt();
System.out.print("Average test score is: " + calcAvergage(test) );
int mark = calcAvergage(test);
System.out.print("Letter grade is: " + determineGrade(mark) );
}
public static int calcAvergage(int test){
Scanner input = new Scanner (System.in);
int total = 0;
int x;
for (x = 1; x <= test; x++)
{
System.out.print("What is the score for test " + x + " : ");
int scores = input.nextInt();
total = total + scores;
}
int average = total/(x-1); //have to do -1 because the final increment value of x is stored as x+1
return average;
}
public static char determineGrade(int average)
{
char mark = 0;
if (average >= 90 && average <= 100)
{
mark = 'A';
}
else if (average >= 80 && average <= 89)
{
mark = 'B';
}
else if (average >= 70 && average <= 79)
{
mark = 'C';
}
else if (average >= 60 && average <= 69)
{
mark = 'D';
}
else if (average <= 60)
{
mark = 'F';
}
return mark;
}
}
Instead of this:
System.out.print("Average test score is: " + calcAvergage(test) );
int mark = calcAvergage(test);
Do this
int mark = calcAvergage(test);
System.out.print("Average test score is: " + mark );
There is no need to call the function twice when you are playing with the return value. Assign it to a variable and then use it.
Like this?
int mark = calcAvergage(test);
System.out.print("Average test score is: " + mark);
From my understanding you do not want to input a number then press enter then enter another number then press enter and so on...
If you say you have 3 test cases in console just type 3 space separated numbers like 10 12 3.
Your question is confusing and your code has logical errors, im sorry. You have if statements using the same logic.(example below) I would say learn up more on programming logic and you will answer your own question
else if (average >= 60 && average <= 69)
{
mark = 'D';
}
else if (average <= 60)
{
mark = 'F';
}
Thx to Avinash Raj for the pointer. I understand now.
the result of the calcAverage is stored in the variable mark, then I can use the int value from the result to both display what the score is as well as display and execute the determineGrade method.

How to pull the maximum and minimum values from an array?

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];
}

Finding min and max using Java

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++;
}

Java: Min/Max/Average (4 variables) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Anyone knows how to run this program using 4 variables only? I tried using 1 variable for min and max "lowhigh" but I was having a hard time figuring out where to put the statements.
int numbers[] = new int[5];
int low = 0; int high = 0;
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
if (count == 0) {
low = number;
high=number;
} else {
if(number < high) {
high= number;
}
if(number > low){
low = number;
}
}
numbers[count] = number;
}
double ave = numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4]/5;
System.out.println("Highest: " +high);
System.out.println("Lowest: " +low);
System.out.println("The average of all number is: " +ave); }}
Another way to do it in Java 8.
int numbers[] = new int[5];
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
numbers[count] = number;
}
LongSummaryStatistics statistics = Arrays.stream(numbers)
.asLongStream()
.summaryStatistics();
System.out.println("Highest: " + statistics.getMax());
System.out.println("Lowest: " + statistics.getMin());
System.out.println("The average of all number is: " + statistics.getAverage());
Looks like your logic is backwards to finding high and low. Also your average wont work because order of operations. Need parens
int numbers[] = new int[5];
int low = Integer.MAX_VALUE; int high = Integer.MIN_VALUE;
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
if (count == 0) {
low = number;
high=number;
} else {
if(number > high) {
high= number;
}
if(number < low){
low = number;
}
}
numbers[count] = number;
}
double ave = (numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4])/5;
System.out.println("Highest: " +high);
System.out.println("Lowest: " +low);
System.out.println("The average of all number is: " +ave); }}
You don't have to use an array if all you're doing is finding the min, max and mean.
final int COUNT = 5; //this is just to be neat, and not needed as a variable.
int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
int sum = 0;
for(int i = 0; i < COUNT; i++){
int n = s.nextInt();//or whatever
if(n > high)
high = n;
if(n < low)
low = n;
sum += n;
}
System.out.println("Max: " + high);
System.out.println("Min: " + low);
System.out.println("Average: " + ((double) sum) / COUNT);
Based on what you mean by 4 variables, this may or may not work. final int COUNT is not really required and 5 can be put in directly instead.
This answer likely goes well beyond the scope of the question, but since the requirements/restrictions are not listed in full, it may still be a valid answer.
With a super strict interpretation of "4 variables", even the Scanner variable s counts.
Using streams, it can be done with 3 variables:
Scanner s; // variable 1
List<Double> values; // variable 2
String line; // variable 3
s = new Scanner(System.in);
values = new ArrayList<>();
while (true) {
System.out.print("Please enter a numbers, or press enter when done: ");
if ((line = s.nextLine().trim()).isEmpty())
break;
values.add(Double.valueOf(line));
}
if (values.isEmpty())
return;
System.out.println("Minimum: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.min().getAsDouble());
System.out.println("Maximum: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.max().getAsDouble());
System.out.println("Average: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.sum() / values.size());
Sample output
Please enter a numbers, or press enter when done: 10
Please enter a numbers, or press enter when done: 42
Please enter a numbers, or press enter when done: 19
Please enter a numbers, or press enter when done: 88
Please enter a numbers, or press enter when done: 1
Please enter a numbers, or press enter when done: 3774
Please enter a numbers, or press enter when done:
Minimum: 1.0
Maximum: 3774.0
Average: 655.6666666666666
There is no point in the numbers[] array; so eliminate that.
You need a control variable for the loop, a temporary storage for the input, then three running variables for min, max and sum (average is sum devided by count, which seems to be fixed to 5).
Thats 5 variables, and you strictly need all of them. Its possible to stuff multiple values into a single variable, but I highly doubt thats what you're supposed to do.
Depending on what the requirements really are (I presume this is homework), one of the five I named above doesn't count as a variable per requirement (most likely the loop control or the temporary input storage).
Edit: Here's a variant using multiple values encoded in one variable that works with three variables (or four if you count the scanner, which I replaced with random for my convinience):
public class HighLowAverage {
public static void main(String[] args) {
long sum = 0;
long highLow = 0x8000_0000_7FFF_FFFFL;
long countNumber = 0;
for (; (countNumber >> 32) < 5; countNumber += 0x1_0000_0000L) {
countNumber = (countNumber & 0xFFFF_FFFF_0000_0000L)
| ((int) (Math.random() * 100) & 0xFFFF_FFFFL);
System.out.println(((countNumber >> 32) + 1) + ". number is: " + (int) countNumber);
sum += (int) countNumber;
if ((highLow >> 32) < (int) countNumber)
highLow = (highLow & 0xFFFF_FFFFL) | (countNumber << 32);
if (((int) highLow) > (int) countNumber)
highLow = (highLow & 0xFFFF_FFFF_0000_0000L) | (countNumber & 0xFFFF_FFFFL);
}
System.out.println("Average: " + ((double) sum) / (countNumber >> 32));
System.out.println("Min: " + (int) highLow);
System.out.println("Max: " + (highLow >> 32));
}
}
The techniques used are bit-shifting and masking to use the upper/lower half of the long datatype as independendly accessible values. Note amount of complicated expressions necessary as well as the numerous constansts in the expressions plus typecasts almost everywhere.
This is code you should never ever use - it works, but even an experienced programmer will need an excessive amount of thinking to figure out if its working correctly. My guess is that a typical beginner class teacher will have trouble understanding it at all.
Edit2: Scratch the above, it can be done with one variable. How? By replacing multiple variables with an array:
public static void main(String[] args) {
long[] vars = new long[5];
vars[1] = Long.MIN_VALUE;
vars[2] = Long.MAX_VALUE;
for (vars[0] = 0; vars[0] < 5; ++vars[0]) {
vars[4] = (int) (Math.random() * 100);
System.out.println((vars[0] + 1) + ". number is: " + vars[4]);
vars[3] += vars[4];
if (vars[4] > vars[1])
vars[1] = vars[4];
if (vars[4] < vars[2])
vars[2] = vars[4];
}
System.out.println("Average: " + ((double) vars[3]) / vars[0]);
System.out.println("Min: " + vars[1]);
System.out.println("Max: " + vars[2]);
}
Needless to say thats still confusing code. Each index of the vars array is used to hold one of the variables (0 = loop control, 1 = min, 2 = max, 3 = sum, 4 = number).
You see it all depends on what is considered a variable.

Counting by factors of two with a while loop?

I want this while loop to print every multiple of two below the number submitted(ex. if 100 was submitted it would print 2 4 8 16 32 64). Here's what I have(I'm only going to include a portion of the class because there was other things in it that don't pertain to this part)
i = 1;
Scanner myScanner = new Scanner(System.in);
System.out.print("Would thoughst be inclined to enter a number fair sir/madam: ");
String answer = myScanner.nextLine();
int number = Integer.parseInt(answer);
System.out.print("Your number set is: ");
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
What this prints if I enter 100 is: 2 4 8 16 32 64 128
How do I get rid of that last number?
You would get rid of that number by modifying your logic to match. Your code is doing precisely what it says. One option is to start at 2, and increase i at the end of the loop instead of just before printing it. You could also use a for loop:
for (int i = 2; i < 100; i *= 2)
...
If you want to save the last power, you have a few options, e.g.:
int k = 2;
for (int i = k; i < 100; i *= 2) {
k = i;
...
}
Or undo the last operation:
int i;
for (i = 2; i < 100; i *= 2)
...;
i /= 2;
Or check the next one:
int i;
for (i = 2; i * 2 < 100; i *= 2)
...;
Checking the next one, in your original form:
while (i * 2 <= number)
...;
Etc.
By the way, your title says "factors", your description says "multiples", and your code says "powers"...
In your code
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
the problem is that i, when it is equal to 64, is indeed less than 100, so the loop continues.
If you change it to
i = 2*i;
while(i <= number)
{
System.out.print(" " + i + " ");
i = 2*i;
}
it does as you wish, because it pre-computes the value before being analyzed as the while-loop terminator.
Try
while( i <= number / 2)
Those are powers of 2, not factors of 2.
"thoughst" is not a word. It should be "thou".
Update the value of i after you print it.

Categories

Resources