Trying to take average each time something is added - java

package gradeAvg;
import java.util.Scanner;
//Grade Average calculater
public class GradeAvg {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Please Enter the first grade being added to the average:");
double average = input.nextInt();
System.out.print("The average is now: " + average + " Please enter the second grade being averaged:");
average += input.nextInt() ;
System.out.print("The average is now: " + average + " Please enter the third grade being averaged:");
average += input.nextInt() / 2;
System.out.print("The average is now: " + average + " Please enter the fourth grade being averaged:");
average += input.nextInt() / 2;
System.out.print("The average is now: " + average + " Please enter the fifth grade being averaged:");
average += input.nextInt() / 2;
input.close();
System.out.print(average);
}
}
Hey guys, I'm really new to java, and pretty terrible at math, I'm supposed to be making a program that allows the user to input a value, have it averaged out, print it out, and then allow the input of another value, have it averaged, and print, and continue. Am i going wrong when I divide by 2 at the end of each input or what?

Average is the sum of all the numbers divided by the number of numbers in the sum.
What you are doing here is not average. You are adding the half of every new number to the total sum. I don't what you are doing here.
Just to make things more understandable, let's make a sum and a counter:
public class GradeAvg {
public static void main(String[] args) {
int sum;
int counter;
// ...
}
}
Each time you ask for a number, you increment the counter and add the new number to sum:
int newNumber;
// ask for input
newNumber = input.nextInt()
sum += newNumber;
counter++;
You can then output the average like this:
System.out.println("The average is: " + (double)sum / counter);

That's wrong. each number you add weight 50% against the other numbers.
you need to keep track of the count (number of elements) and the sum and each time divide the sum by the number of elements.
so each time you add a number the function should be:
(OLD_AVERAGE*OLD_COUNT+NEW_NUMBER)/(OLD_COUNT+1)
or just use SUM and COUNT and each time AVERAGE=SUM/COUNT.
inc. count by 1 every new number.
inc sum by the number entered.

complete working solution... hope it helps...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
int count = 1;
double average = 0;
System.out.print("Please Enter the " + count + " grade being added to the average:");
for (; count <= 5;) {
sum = sum + input.nextInt();
average = sum / count;
System.out.println("The average is now: " + average);
count++;
if (count <= 5)
System.out.println("Please enter the " + count + " grade being averaged:");
}
input.close();
}

Related

Count numbers in a "for loop" and give back average, min, max value in java

A user should input a number "x", and then the count of "x" numbers, e.g. input = 3, then 3 random numbers like 3, 5, 7.
Afterwards the program should give an output of the average, min and max value of this "x" numbers. So it has to read the numbers, but i don't know how it can be done.
It should be done without arrays and with a for loop.
I didn't find a possible solution here, but maybe I didn't do the right search.
So here is what i got so far:
import java.util.Scanner;
public class Statistic
{
public static void main (String[] args)
{
// Variables
Scanner input = new Scanner(System.in);
int number1;
int numbers;
double averageValue;
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Pls enter a number: ");
number1 = input.nextInt();
System.out.print(" Pls enter " + number1 +" numbers: ");
numbers = input.nextInt();
for (int count = 0; count < number1; count ++) {
System.out.println(numbers); //Just for me to see which numbers are read by the programm
}
averageValue = numbers / number1;
// Output
System.out.println("\n Biggest number: " + Math.max(numbers));
System.out.println("\n Smallest number: " + Math.min(numbers));
System.out.print("\n Average value: " + averageValue);
}
}
But it only prints out and calculates with the first number of the "numbers"-input. Further I am not sure how to use the "Math.max" for a random count of numbers.
The problem is here:
System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");
numbers = input.nextInt();
nextInt() only saves one int. Every subsequent number you are entering gets lost, of course.
What you need to do is to move this statement inside the for loop for your idea to work.
Also, you can't use min and max here. min and max compare two numbers and return the greater of the two. For your purpose, you'd need to check inside the loop which the greatest and smallest number is and then output it accordingly.
You will need 6 variables: min = 0, max = 0, avg, sum = 0, count, num.
(avg variable is optional)
Program flow will be:
input how many numbers you want to enter -> store in variable count
use some loop to loop count number of times and in each iteration store
users value in variable num.
Increment sum by number user entered. sum += num;
check if entered number is less than current min. If true store min as that number.
Same as min do for max variable.
When loop exit you will have min, max, sum and count variables stored. To calculate avg devide sum with count and there you go. avg = sum / count.
First your code is logically in correct. when u have to take min and max values with average u need to store the inserted elements or process each input(for time complexity this would be the best approach).
Below I have modified your code where i m using enter code hereJava Collections List to store the inputs, sort them and get the data.
After sorting first will me min and last will be max.
Math.min and Math.max only works for comparing 2 numbers not an undefined list.
Again i would say the best solution would be if u check for the number is min or max at input time.
As you are new to java you can try that out your self.
import java.util.*;
public class ZahlenStatistik
{
public static void main (String[] args)
{
// Variables
Scanner input = new Scanner(System.in);
int number1;
List<Integer> numbers = new ArrayList<Integer>(); // change it to list
double averageValue;
int sum= 0;
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Bitte geben Sie eine Zahl ein: ");
number1 = input.nextInt();
System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");
//Define the number of times loop goes
for (int count = 0; count < number1; count ++)
{
numbers.add(input.nextInt());
}
for(Integer number:numbers)
{
sum = sum + number;
}
averageValue = sum / number1;
Collections.sort(numbers);
// Output
System.out.println("\n Die größte Zahl ist: " + numbers.get(numbers.size()-1));
System.out.println("\n Die kleinste Zahl ist: " + numbers.get(0));
System.out.print("\n Der averageValue betr\u00e4gt: " + averageValue);
}
}
Some errors that I can see
System.out.print(" Pls enter " + number1 +" numbers: ");
numbers = input.nextInt();
You need here a loop and array to read and store all elements.
To get average value you need first to sum all elements in array and then to divide by length of array.
To find min and max values in array you cannot use Math.min() and Math.max() methods because these methods get two parameters and return min/max value.
Your code should be something like this
Notes
If you cannot use Java 8 you must replace Arrays.stream(numbers).max().getAsInt(); and Arrays.stream(numbers).min().getAsInt(); with helper methods which find max/min values in an array.
If you can use Java 8 you can calculate sum int sum = Arrays.stream(numbers).reduce(0, (x, y) -> x + y); instead in for loop.
.
public class Statistic {
public static void main(String[] args) {
// Variables
Scanner input = new Scanner(System.in);
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Pls enter a number: ");
int number1 = input.nextInt();
System.out.println(" Pls enter " + number1 + " numbers: ");
int[] numbers = new int[number1];
for (int i = 0; i < number1; i++) {
System.out.println("Enter next number");
numbers[i] = input.nextInt();
}
// Find min and max values
int max = Arrays.stream(numbers).max().getAsInt();
int min = Arrays.stream(numbers).min().getAsInt();
System.out.println("\n Biggest number: " + max);
System.out.println("\n Smallest number: " + min);
// Get average value
int sum = 0;
for (int num : numbers) {
sum = sum + num;
}
double averageValue = (double) sum / number1;
System.out.print("\n Average value: " + averageValue);
}
}
import java.util.Scanner;
public class SumOf2
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter 2 integer values");
int m = s.nextInt();
int n = s.nextInt();
int sum=0;
int count=0;
for(int i=m ; i<=n ; i++)
{
if(count < n)
{
sum=sum+i;
count++;
}
}
System.out.println("Sum of two numbers is: "+sum);
System.out.println("Count between 2 numbers is : "+count);
}
}

Java averaging calculator with defined number of entries

I've seen several average calculators but none with this specific function.
Basically, I want it to ask "How many numbers would you like to average?" then "Enter your number" and continue to prompt "Enter your number" after each entry until the "How many numbers..." quantity is fulfilled. I know it's a count-loop (sorry if my jargon is off...I'm only in my second semester of computer programming) but I don't know how to set it up. Thanks in advance for your answers. Here's what I have so far:
import java.util.Scanner;
public class TestScoreApp
{
public static void main(String[] args)
{
// welcome the user to the program
System.out.println("Welcome to the Test Average Calculator!");
System.out.println(); // print a blank line
// display operational messages
System.out.println("Please enter test scores that range from 0 to 100.");
System.out.println(); // print a blank line
// initialize variables and create a Scanner object
int scoreTotal;
int scoreCount;
int testScore;
Scanner sc = new Scanner(System.in);
// perform calculations until choice isn't equal to "y" or "Y"
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
// get the number of grades to be averaged from the user
System.out.print("How many scores would you like to average? ");
scoreCount = sc.nextInt();
// get the input from the user
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreTotal = scoreTotal + testScore;
}
else if (testScore >= 100)
System.out.println("Invalid entry, not counted");
// display the score count, score total, and average score
double averageScore = scoreTotal / scoreCount;
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n";
System.out.println(message);
System.out.print("Would you like to average more grades? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
Your approach is near about right except some mistakes. You want to take input until 'n' is pressed and then the average would be shown. That means the average calculation must be done outside the loop, when taking input ends.
If you want to take input with a predefined number from input instead of 'y'/'n' approach, you can reuse your while loop:
int numOfInput = sc.nextInt(); // how many number will be entered
while(numOfInput > 0) {
// take every input and add to total
--numOfInput;
}
// average calculation
Also, a little logical mistake in input validation check.
if (testScore <= 100) // for less or equal 100
{
scoreTotal = scoreTotal + testScore;
}
else if (testScore >= 100) // for greater or equal 100
System.out.println("Invalid entry, not counted");
Both condition checks whether the number is equal to 100, which is not expected. If you allow only number less than 100, then you could write:
if (testScore < 100) {
scoreTotal += testScore;
}
else {
System.out.println("Invalid entry, not counted");
}
So you want to average scoreCount items, or keep averaging until the user has input "n" ?
If it's the first case (As you've described in your question) and you want to average for scoreCount times, you need to change the condition on your while loop.
System.out.print("How many scores would you like to average? ");
scoreCount = sc.nextInt();
scoreTotal = 0;
for(int i=0; i<scoreCount; i++){
scoreTotal += sc.nextInt();
System.out.print("Okay please enter next...");
}
System.out.print("Average is " + scoreTotal/scoreCount);
If you want to do it with a while, just keep an index, int index=0;, increment the index on each iteration and check if you've exceeded the index.
while (index < scoreCount)
scoreTotal += sc.nextInt();
index++;
System.out.print("Average is " + scoreTotal/scoreCount);
That is what you need:
for( int i = 0; i < scoreCount; i++){
System.out.print("Enter score: ");
testScore = sc.nextInt();
}
The for loop creates integer i to hold its looping index
int i;
And each loop asks is i bigger than scoreCount and if not loop again.
i < scoreCount;
And after each loop it adds one to i.
i++

grade avg calculator not returning correct answer

This is a program to calculate average grades and I cant figure out whats wrong with my code. It is returning the wrong answer.
Editing post to remove personal information.
:
/**
* This program will calculate grade average of user input
* Date: 10/2/2015
*/
import java.util.Scanner;
public class GradeAVG {
public static void main(String[] args) {
avgGrade();
}
public static void avgGrade() {
Scanner keyboard = new Scanner (System.in);
double count = 0;
double avgGrade = 0 ;
double grade;
double total = 0;
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
while(true){
System.out.println("Please input the grade");
grade= keyboard.nextDouble();
count = count + 1;
if (grade < 0) break;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
}
Output:
Please input the grade
100
Please input the grade
50
Please input the grade
-9
Sum is 50.0
The average of the 2 grades are 50.00
Sum should have been 150 and average 75.
The problem is that you are reading a grade from the user before the while loop begins and you are ignoring this value afterwards.
You should remove those 2 lines and things will work as expected. I commented those lines in the snippet below to explicitely show you the problem.
public static void avgGrade() {
Scanner keyboard = new Scanner(System.in);
double count = 0;
double avgGrade = 0;
double grade;
double total = 0;
// System.out.println("Please input the grade");
// grade = keyboard.nextDouble();
while(true){
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
count = count + 1;
if (grade < 0) break;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
As a side note, you should always try to minimize the scope of each of your variable. Here, the grade variable is only use inside the while loop so you can directly write double grade = keyboard.nextDouble(); and remove the declaration in the beginning of the method.
You are not adding the first grade which you are accepting outside of the while loop to the total.
Also there is no point in incrementing the count, if the grade is not acceptable, so increment your count only after the grade check.
You can rewrite your while block something like
while (true) {
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
if (grade < 0)
break;
count = count + 1;
total += grade;
}
avgGrade = total / count;
System.out.println("Sum is " + total);
System.out.printf("The average of the %.0f grades are %.2f ", count,
avgGrade);
}
Thanks guys. Here is the final code
/**
* This program will calculate grade average of user input
*
* Date: 10/2/2015
*/
import java.util.Scanner;
public class GradeAVG {
public static void main(String[] args) {
avgGrade()
}
public static void avgGrade()
{
Scanner keyboard = new Scanner (System.in);
double count = 0;
double avgGrade = 0 ;
double total = 0;
while(true){
System.out.println("Please input the grade");
double grade= keyboard.nextDouble();
if (grade < 0) break;
count = count + 1;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
}
Several problems:
First, you do two assignments into grade before first reading from it (first one before the while loop and second inside the while loop), so the first input will be ignored entirely
Second, you increment the count variable before checking whether to break the while loop, so you end up with count higher by 1 than should be
Third, the average is computed inside the loop and will not be recalculated in the last (partial) iteration
The program will go like this:
input: 100, count: 0, total: 0, avg: 0
input was ignored
input: 50, count: 1, total: 50, avg: 50
input: -9, count: 2, total: 50, avg: 50
loop exit, but incremented count before; did not recalculate avg

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

Four Numbers Program: Grouping numbers

I created a program that enables you to type in four numbers that must have specific requirements:
-must be a multiple of 4 or 6
-if greater than 500, must be a multiple of 10
The program takes the four numbers and gives you the sum of them, the average of them, shows you the smallest of the four numbers and finally the largest of the four numbers.
Now I want to try and display a group that each number belong to. I want these groups if you were wondering:
Group Tens if the number is between 0 and 99
Group Hundreds if the number is between 100 and 999
Group Thousands if the number is between 1000 and 999,999
Group Others if the number is greater than 999,999
My problem is I do not know where I should being placing them into my program (below)
import java.util.Scanner;
public class FourNumbersProgram {
private static int readNumber(String message, Scanner in) {
System.out.println("Enter a numbers divislbe by 4 or 6. No negatives.");
System.out.println("**If greater than 500: must be multiple of 10");
System.out.print(message);
while (!in.hasNextInt()) {
in.next();
System.out.println("Sorry, couldn't understand you!");
System.out.print(message);
}
int a = in.nextInt();
return a;
}
private static int readNumberToMatchCondition(String message, Scanner in) {
int number = 0;
do {
number = readNumber(message, in);
if (number < 500) {
if (number % 4 != 0 && number % 6 != 0) {
System.out.println(number + " not divisible by 4 or 6");
} else {
return number;
}
} else {
if (number % 4 != 0 && number % 6 != 0) {
System.out.println(number + " not divisible by 4 or 6");
} else if (number % 10 != 0) {
System.out.println(number + " is greater than 500 and not divisible by 10");
} else {
return number;
}
}
} while (true);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int randomNumber1 = readNumberToMatchCondition("Enter first number:", in);
int randomNumber2 = readNumberToMatchCondition("Enter second number:", in);
int randomNumber3 = readNumberToMatchCondition("Enter third number:", in);
int randomNumber4 = readNumberToMatchCondition("Enter fourth number:", in);
int sum; // sum of number1, number2, number3, and number4
int avg; // average of number1, number2, number3, and number4
int largest; // largest number of the four integers
int smallest; // smallest number of the four integers
sum = (randomNumber1 + randomNumber2 + randomNumber3 + randomNumber4);
avg = ((sum) / 4);
smallest = randomNumber1;
smallest = (randomNumber2 < smallest) ? randomNumber2 : smallest;
smallest = (randomNumber3 < smallest) ? randomNumber3 : smallest;
smallest = (randomNumber4 < smallest) ? randomNumber3 : smallest;
largest = randomNumber1;
largest = (randomNumber2 > largest) ? randomNumber2 :largest;
largest = (randomNumber3 > largest) ? randomNumber3 :largest;
largest = (randomNumber4 > largest) ? randomNumber4 :largest;
System.out.println();
System.out.println("First number entered: " + randomNumber1); //prints first number entered
System.out.println("Second number entered: " + randomNumber2); //prints second number entered
System.out.println("Third number entered: " + randomNumber3); //prints third number entered
System.out.println("Fourth number entered: " + randomNumber4); //prints fourth number entered
System.out.println();
System.out.println("The sum is: " + sum); //prints sum of four numbers
System.out.println("The average is: " + avg); //prints average of four numbers
System.out.println("The smallest number is: " + smallest); //prints smallest of the four numbers
System.out.println("The largest number is: " + largest); //prints largest of the four numbers
System.out.println();
}
}
Here is a transcript of my code:
my professor gave me this sample of a grouping program (below)
import java.util.Scanner;
public class Prog2 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);// read a number
System.out.println("Enter a number: ");
int number = in.nextInt();
if (number < 0) {
System.out.println("Error: Sorry, no negative numbers allowed.");
System.exit(0);
}
int grp1 = (number / 100) + 1;
int grp2 = (number / 1000) + 1;
int grp3 = (number / 1000000) + 1;
switch (grp1){
case 1: // Group Tens
System.out.println(number + " belongs to Group Tens");
break;
default:
switch (grp2) {
case 1:// Group Hundreds
System.out.println(number + " belongs to Group Hundreds");
break;
default:
switch (grp3) {
case 1:// Group Thousands
System.out.println(number + " belongs to Group Thousands");
break;
default:// Group Others
System.out.println(number + " belongs to Group Others");
}
}
}
in.close();
}
}
Heres a transcript of his code:
I know his program is asking for the user to type in one number and the program groups it. I was wondering how to put something like this into my program. I am confused because I have four numbers that have to be grouped and I'm not sure if I have to repeat something similar to my professors program for all of my four numbers (randomNumber1, randomNumber2, randomNumber3, randomNumber4
Please no positing an entire corrected code! I want to fix it myself and learn!
Your professors program will work for all of your numbers. All you need to do is call the method 4 times. Once for each number. What you need to do is put his code into a method on it's own. (Remember, if he's given it to you as a guide, then he will probably want you to give a go at writing the logic yourself).
Let's say you put his code in a method that looks like:
public void displayNumberGroup(int number)
{
// Displays number group using your prof's code.
}
Then, next, all you need to do is pass each value that you've loaded, into that method. For example: displayNumberGroup(randomNumber1);. This will calculate the grouping for that number. I'll leave it up to you to put this stuff into context, since you've requested to not be spoonfed the answer (which is very commendable!).
Instead of doing randomNumber1, randomNumber2, ect you can make them into an array. By doing that, you can then put a for loop over the given switch and run it 4 times so all of your numbers have groups. If you need me to explain any part of this with a simple example I will, but I know you want to do most of this yourself so if you have any questions let me know.

Categories

Resources