How would I total two sets of numbers entered by a user? - java

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

Related

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

Java sum of numbers error

This code seems to run well, but am getting error message regarding calculating the sum of the integers entered.
The point of the exercise is to input a series of numbers, and after the value -1 is entered, calculate the sum of the numbers, how many numbers were entered, the mean value, and the number of odd and even numbers.
The output I get suggests the program is running fine, but still get an eror message.
With input 1 17 2 18 17 -1 should print "sum: 55" expected:<55> but was: <0>
Apologies in advance if my Java syntax is a bit inelegant. I'm fairly new at this! Code below.
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type numbers: ");
int n;
double sum = 0.0;
int i = 0;
double average = 0.0;
int odd = 0;
int even = 0;
while (true) {
n = Integer.parseInt(reader.nextLine());
if (n != -1) {
System.out.print("Type numbers: ");
sum += n;
i++;
average = sum / i;
if (n % 2 == 0) {
even++;
} else {
odd++;
}
} else {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + i);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
break;
}
}
}
}
You're printing 55.0. It seems you're getting this program tested by another program which you don't have access to the source code of.
Issue 1
You probably want to print 55 specifically.
Instead of:
double sum = 0.0;
Do:
int sum = 0;
Issue 2
Use int over double. Cast to double for the average value.
Then instead of this:
average = sum / i;
Do something like:
average = (double)sum / i;
Issue 3
Also, it seems the error message wants you to print as sum: 55.
So change this:
System.out.println("The sum is " + sum);
To:
System.out.println("sum: " + sum);

Getting the overall average

I'm trying to get the overall average of the grades. I was able to get the average of each individual grade. Now just to get the total I'm not sure how to get it.
My output is:
Quizzes:66.0
Labs:88.0
Lab_atendance: 81.0
Midterms:91.0
public static double average(int[] scoreArray, int numScores,
int maxGrade, String name) {
double sum = 0;
for (int i = 0; i < scoreArray.length; i++) {
sum += scoreArray[i];
}
double average = Math.round((sum / numScores)*100/maxGrade);
System.out.println( name + ":" + average+" %");
return average;
}
What you are doing in not average exactly! but still..
Do the same procedure for Quizzes, Labs, Lab_attendance and Midterms! Isn't it obvious?
Here your numScores will be 4!
So from your given input
Avg = ((66.0 + 88.0 + 81.0 + 91.0) / 4) * 100 / maxGrade)
Your average calculation (and method signature) seem incorrect (averages are not calculated by dividing a "max"), I would use something like
// Note the new method signature - name then a variable number of scores.
public static double average(String name, int... scores) {
double sum = 0;
for (int score : scores) { // <-- for each loop.
sum += score;
}
final double average = (scores != null) ? sum / scores.length : 0;
System.out.println(name + ":"
+ Math.round(average * 100) + " %"); //<-- Display as a percentage
return average;
}

String not printing out after conclusion of loop

So after browsing the already asked questions on here and other sites I figured I would give this a go.
I am working on an exercise that wants you to set up a program in Java that takes an input of 10 numbers and computes the average(mean) and the standard deviation and outputs them.
My problem is that when I run the program, and then enter my desired 10 values and hit enter, nothing happens. For some reason the System printouts that occur after the loop are not being executed. The println inside the loop is not necessary, but is just to show that the values are being calculated correctly as the loop runs, and they are.
I am aiming to have the current value that myValues is assigned to to be added to sum1, and the square of myValues to be added to the sqrdSum. sqrdSum is just a variable I made to sum the squares of the values entered so that the calculation of standard deviation later in the program will be cleaner.
As expected, I am not looking for this to be done for me, just some advice on how to adjust my code such that the printlns at that occur after the loop will execute. I am expecting it to be something to do with my logic, but can not figure it out. Hopefully it is something simple I have managed to miss.
Thanks.
So far I have set it up using a for loop:
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = sum1 / n;
double std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = input1.nextDouble();
for (int count = 0; count <= n; count++) {
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
myValues = input1.nextDouble();
}
System.out.print("The mean of your values is: " + mean1);
System.out.print("The standard deviation of your values is: " + std1);
//Test values: 1 2 3 4.5 5.6 6 7 8 9 10
//Should give a mean of 5.61
//std of 2.99794
The problem is, that input1.nextDouble() blocks until the next number is entered. You are entering 10 numbers, but you expect 11 inputs, since you have this line
double myValues = input1.nextDouble();
which executes once and
myValues = input1.nextDouble();
inside the loop which executes 11 times. Just move it at the beginning of the loop:
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = 0;
for (int count = 0; count < n; count++) {
double myValues = input1.nextDouble();
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
}
As Brian noted, you also have an off-by-one error. You start at 0 but count to 10, that makes 11 loop cycles. Change <= to <
Just change count <= n to count < n in your cycle. You're accidentaly expecting one too many values.
While the answers given did solve your original problem there is also another problem with your code. You won't be getting the correct mean because of how you initiate it and then don't set it to any values after your for loop.
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = sum1 / n;
double std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
The lines above should read,
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = 0.0;
double std1 = 0.0;
and then after your for loop you should calculate mean1 and std1 like the code below.
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = 0.0;
double std1 = 0.0;
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = 0.0;
for (int count = 0; count < n; count++) {
myValues = input1.nextDouble();
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
}
mean1 = sum1 / n;
std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
System.out.print("The mean of your values is: " + mean1);
System.out.print("The standard deviation of your values is: " + std1);
//Test values: 1 2 3 4.5 5.6 6 7 8 9 10
//Should give a mean of 5.61
//std of 2.99794

Using Java Arrays to get min & max

thank you for your help.
Here is the assignment:
Computer Technology Instructor has a small class of 10 students. The instructor evaluates the performance of students in the class by administering 2 midterm tests and a Final Exam.
Write a program that prompts the instructor to enter the 10 grades of midterm 1 and store these numbers in an array. Next prompt for the 10 grades of midterm 2 and store these numbers in a different array. Next prompt for the 10 grades of the Final Exam and store these in a different array. Next add midterm1 to midterm2 to Final and store the totals in a different array. Next, scan the array that has the totals and identify the minimum grade and maximum grade. Inform the instructor of the minimum grade and maximum grade.
The two bold phrases are where I am having problems. Everything works except for the minimum grade and maximum grade. Here is what it tells me, after I've only entered numbers between 65 and 100:
The highest test score is: 276 The lowest test score is: 249
Here is my code:
import java.util.Scanner;
public class Arrays {
public static void main(String[] args) {
// Create a scanner
Scanner input = new Scanner(System.in);
// Prompt for the 1st mid term
int [] midTerm1 = new int[10];
int [] midTerm2 = new int[10];
int [] finalExam = new int[10];
int [] grades = new int[10];
for (int i = 0; i < midTerm1.length; i++){
System.out.println("Enter the 10 Mid Term 1 grades: ");
midTerm1[i] = input.nextInt();
}
// Prompt for the 2nd mid term
for (int i = 0; i < midTerm2.length; i++){
System.out.println("Enter the 10 Mid Term 2 grades: ");
midTerm2[i] = input.nextInt();
}
// Prompt for Final grades
for (int i = 0; i < finalExam.length; i++){
System.out.println("Please enter a Final Exam grade: ");
finalExam[i] = input.nextInt();
}
for (int i = 0; i < grades.length; i++){
grades[i] = (midTerm1[i] + midTerm2[i] + finalExam[i]);
}
int minGrade = grades[0];
int maxGrade = grades[0];
for (int i = 0; i < grades.length; i++)
{
if (minGrade > grades[i])
minGrade = grades[i];
if (maxGrade < grades[i])
maxGrade = grades[i];
}
System.out.print("The highest test score is: " + maxGrade);
System.out.print("The lowest test score is: " + minGrade);
}
}
Edit:
grades[i] = (midTerm1[i] + midTerm2[i] + finalExam[i]);
Your code may in fact be correct. Since you're adding your three test scores together, expect that the grade will be not between 65 and 100 but rather between 195 and 300.
If you want a number between 65 and 100, this needs to be divided by 3:
grades[i] = (midTerm1[i] + midTerm2[i] + finalExam[i]) / 3;
or else find some other way to normalize the grades. For instance, if the final is 50% of the grade then you could have:
grades[i] = (25 * midTerm1[i] + 25 * midTerm2[i] + 50 * finalExam[i]) / 100;
But again your current solution may in fact be the correct one.

Categories

Resources