Input numbers until 0, then calculate average - java

Okey, i need to make a program to calculate average. But, i need to input numbers, and when i want to stop i can input zero. Then, my program need to sum all entered numbers and calculate average of entered numbers. I made almost everyithing in my code but idk how to make a formula to calculate average, my program sum numbers and then divide by last entered number.
Scanner input = new Scanner(System.in);
System.out.println("Input numbers, 0 for stop!");
int number = input.nextInt();
int number1 = 1;
while (number != 0) {
number1 = (number + number1) / number; //here is my problem?
number = input.nextInt();
}
System.out.println("Average is: " + number1);

Your code is written great except you calculate the average wrong,
If you want to calculate the average on the fly you will need to know how much numbers you have read so far..
e.g:
Scanner input = new Scanner(System.in);
System.out.println("Input numbers, 0 for stop!");
int number = input.nextInt();
int average = number;
int counter = 1;
while (number != 0) {
average= (average * counter + number) / (counter + 1);
counter++;
number = input.nextInt();
}
System.out.println("Average is: " + average);
this code will give you the average after each step.
Another (simpler solution) is:
Scanner input = new Scanner(System.in);
System.out.println("Input numbers, 0 for stop!");
int number = input.nextInt();
double sum = 0;
int counter = 0;
while (number != 0) {
sum += number;
counter++;
number = input.nextInt();
}
System.out.println("Average is: " + sum/counter);

Average is the sum total of the numbers divided by the number of numbers, so you need to keep a running count of how many numbers you are inputting, as well as a running sum, and at the end, you divide the sum by the count. The sum should be a double just in case you end up with a fraction
Scanner input = new Scanner(System.in);
System.out.println("Input numbers, 0 for stop!");
double sum = 0;
int count = 0;
int number = input.nextInt();
while (number != 0) {
sum += number;
count++;
number = input.nextInt();
}
System.out.println("Average is: " + sum/count);

Related

Read a list of nonnegative integers and to display the largest integer, the smallest integer and the average of all the integers

I have encountered some problems with the calculating of largest and smallest number... If the first number I entered is a larger number than the 2nd number input, it will not record the 1st number into the largest...
Take a look at the output, it will help elaborate better..
Calculation Error.. &
1st input problem..
Codes below!
public static void main(String[] args) {
int smallest = Integer.MAX_VALUE;
int largest = 0;
int number;
double totalAvg = 0;
double totalSum = 0;
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Enter few integers (Enter negative numbers to end input) :");
while (true) { //LOOP till user enter "-1"
number = kb.nextInt();
//Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
count = count + 1;
}
if (number < smallest) { //Problem 1 : If 1st input num is bigger than 2nd input num,
smallest = number; // largest num will not be recorded..
} else {
largest = number;
}
totalSum = totalSum + number;
totalAvg = (totalSum / count);
}
System.out.println("The smallest number you have entered is : " + smallest);
System.out.println("The largest number you have entered is : " + largest);
System.out.println("The total sum is : " + totalSum);
System.out.println("The total average is : " + totalAvg);
System.out.println("Count : " + count);
} // PSVM
You could build an IntStream if you are using Java 8, and extract those numbers automatically using IntSummaryStatistics. You can find the official documentation from Oracle here.
Here is the code to achieve that:
List<Integer> input = new ArrayList<>();
while (true) { // LOOP till user enter "-1"
number = kb.nextInt();
// Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
input.add(number);
}
}
IntSummaryStatistics z = input.stream() // gives Stream<Integer>
.mapToInt(Integer::intValue) // gives IntStream
.summaryStatistics(); // gives you the IntSummaryStatistics
System.out.println(z);
If you input 8 3 7 the output will be:
IntSummaryStatistics{count=3, sum=18, min=3, average=6.000000, max=8}
I hope it helps!
Do it like this:
public static void main(String[] args) {
int smallest = Integer.MAX_VALUE;
int largest = 0;
int number;
double totalAvg = 0;
double totalSum = 0;
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Enter few integers (Enter negative numbers to end input) :");
while (true) { //LOOP till user enter "-1"
number = kb.nextInt();
//Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
count = count + 1;
}
if (number < smallest) { //Problem 1 : If 1st input num is bigger than 2nd input num,
smallest = number; // largest num will not be recorded..
}
//REMOVED ELSE ADDED another IF
if (number > largest){
largest = number;
}
totalSum = totalSum + number;
totalAvg = (totalSum / count);
}
System.out.println("The smallest number you have entered is : " + smallest);
System.out.println("The largest number you have entered is : " + largest);
System.out.println("The total sum is : " + totalSum);
System.out.println("The total average is : " + totalAvg);
System.out.println("Count : " + count);
} // PSVM
The problem is your if statement, as the logic is flawed. If the input number is smaller than smallest, then you update the smallest number. So far all is correct. The problem occurs, because you update largest in the else part. This means, if a number is not the smallest, largest is overwritten. But if the number is greater than the smallest, it is not automatically the largest. The right way to do this, is to check if the number is larger than the largest in a new if statement and update largest only in this case.

Find mean and standard deviation using loops

My goal is to calculate the mean and standard deviation of 10 numbers obtained from user input.
I learned only while loops in my class.
Question:
How can I assign each user input (inside the loop) to a separate variable, to later compare to the mean, to find the standard deviation?
(I haven't taught about arrays in my class. So, I have to solve this without using arrays)
I did the program a very long a tedious way but can provide more code if needed to show I can do while loops to find mean.
import java.util.Scanner;
public class StandardDev
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
double num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, num6 = 0, num7 = 0, num8 = 0, num9 = 0, num10 = 0, total = 0, mean = 0, stDev1 = 0, stDev2 = 0, sum = 0;
System.out.println("Enter 10 numbers: ");
num1 = input.nextDouble();
num2 = input.nextDouble();
num3 = input.nextDouble();
num4 = input.nextDouble();
num5 = input.nextDouble();
num6 = input.nextDouble();
num7 = input.nextDouble();
num8 = input.nextDouble();
num9 = input.nextDouble();
num10 = input.nextDouble();
sum = num1+num2+num3+num4+num5+num6+num7+num8+num9+num10;
mean = sum / (double) 10;
stDev1 = Math.pow(num1 - mean, 2) + Math.pow(num2 - mean, 2) + Math.pow(num3 - mean, 2) + Math.pow(num4 - mean, 2) + Math.pow(num5 - mean, 2) +
Math.pow(num6 - mean, 2) + Math.pow(num7 - mean, 2) + Math.pow(num8 - mean, 2) + Math.pow(num9 - mean, 2) + Math.pow(num10 - mean, 2);
stDev2 = Math.sqrt(stDev1 / 10);
System.out.println ("The mean is " + mean + ".");
System.out.println ("The standard deviation is " + stDev2 + ".");
}
}
Here is what I have for finding mean. My logic tells me I can only find standard deviation if I can access those inputs individually to subtract from mean and square. Not sure how though..
import java.util.Scanner;
public class JTillman03_45
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int count = 0, total = 0;
double mean, stDev = 0;
System.out.println("Enter a digit: ");
int number = input.nextInt();
while (count < 9){
total += number;
count++;
System.out.println("Enter a digit: ");
number = input.nextInt();
}
mean = total / (double) count;
System.out.println("The mean of those numbers is: " + mean);
System.out.println("The standard deviation of those numbers is: " + stDev);
}
}
Do you really need to store all the integers? If not, you can compute the average and standard deviations with the three following values:
How many numbers were entered (in your problem, it is a fixed value 10).
The sum of all numbers.
The sum of the squares of the numbers.
Which gives
double count = 10.0; // is 10.0 for your problem
double sum1 = 0.0; // sum of the numbers
double sum2 = 0.0; // sum of the squares
int i;
for (i=0; i < 10; i++) {
System.out.println("Enter 10 numbers: ");
double n = input.nextDouble();
sum1 += n;
sum2 += n * n;
}
double average = sum1 / count;
double variance = (count * sum2 - sum1 * sum1) / (count * count);
double stdev = Math.sqrt(variance);
For summing up 10 user-inputted numbers, you can keep track of the sum using just one variable and the += operator. No need to have so many variables, that's what the loop is for! For example,
double sum = 0;
Scanner input = new Scanner (System.in);
int counter = 1;
System.out.println("Enter 10 numbers: ");
//adds up 10 user-inputted numbers
while(counter <= 10){
sum += input.nextDouble();
//how the loop will end after 10th iteration
counter++;
}
double mean = sum/10; //no need for double cast here since sum is a double
Without arrays, it would be hard to calculate the standard deviation using loops since we need access to the individual numbers to find the standard deviation. Therefore, your solution is really the only way unless we have the user input the same 10 numbers again using a while loop similar to above to find the variance. For example,
//reset counter
counter = 1;
double variance = 0;
System.out.println("Enter 10 numbers: ");
while(counter <= 10){
variance += Math.pow(input.nextDouble()-mean,2);
counter++;
}
double stdDev = Math.sqrt(variance/10);
System.out.println ("The mean is " + mean + ".");
System.out.println ("The standard deviation is " + stdDev + ".");
Using a while loop, iterate the values of input.nextDouble() as the condition of the loop. as long as there is input, the loop will keep going. At the same time, keep a count of the number of inputs and the sum of the numbers. Just with those 2 numbers, you can calculate the mean and the standard deviation. If you look at stDev1 you can see it is just the sum of the numbers minus the mean times 10 (or the count of inputs). The mean is just the sum divided by the count of inputs. If you need more explanations, let me know. I will be adding some example code shortly.
public class StandardDev {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
sum += input.nextDouble();
count++;
}
mean = sum / count;
stdDev = sum - (count * mean);
System.out.println("The mean is " + mean + ".");
System.out.println("The standard deviation is " + stdDev + ".");
}
}
Here is updated code with loops.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
double sqSum = 0;
System.out.println("Enter 10 numbers: separte by space");
for ( int i = 0 ; i < 10 ; i++){
double val = input.nextDouble();
sum += val;
sqSum += val * val;
}
double mean = sum / 10;
double stdDev = sqSum / 10 - mean * mean;
System.out.println("The mean is " + mean + ".");
System.out.println("The standard deviation is " + stdDev + ".");
}

Java-Number of scores needs to be one less in answer

So here is my code:
package e7;
import java.util.Scanner;
public class Q1 {
public static void main(String[] args)
{
double[] scores = new double[10];
double sum = 0.0D;
int count = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a new score (-1 to end): ");
scores[count] = sc.nextDouble();
if (scores[count] >= 0.0D)
sum += scores[count];
}
while (scores[(count++)] >= 0.0D);
System.out.println("The total number of scores is: " + count );
double average = sum / (count - 1);
int numOfAbove = 0;
int numOfBelow = 0;
for (int i = 0; i < count - 1; i++) {
if (scores[i] >= average)
numOfAbove++;
else
numOfBelow++;
}
System.out.printf("Average is " + "%.2f\n",average);
System.out.println("Number of scores above or equal to the average " + numOfAbove);
System.out.println("Number of scores below the average " + numOfBelow);
}
}
How do make it display the correct number of scores calculated? If I input 2 numbers and then do the -1 one to end it keeps saying 3 scores. Should only be two. How do I fix this? Thanks
System.out.println("The total number of scores is: " + count );
You probably want:
System.out.println("The total number of scores is: " + (count - 1));
You could also change your loop from a do while to a while loop as follows,
while (true) {
System.out.print("Enter a new score (-1 to end): ");
double tempDouble = sc.nextDouble();
if (tempDouble >= 0.0D)
scores[count] = tempDouble;
sum += scores[count];
count++;
else
break;
}
That way as if your double input isn't correct it would break out of the while loop when the user entered -1. You might have to tweak it a bit for your use case.

Write a program that reads an unspecified number of integers

"Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers , determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number."
I don't know what I did wrong
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int positive = 0, negative = 0, total = 0, count = 0;
double average;
System.out.println("Enter the number: ");
int number;
while ((number = input.nextInt()) != 0) {
total += number;
count++;
if (number > 0) {
positive++;
} else if (number < 0) {
negative++;
}
}
average = total / count;
System.out.println("The number of positives is " + positive);
System.out.println("The number of negatives is " + negative);
System.out.println("The total is " + total);
System.out.printf("The average is %d ", average);
}
}
First: it should be average = (double)total / count; because int / int than you get an integer.
Second: System.out.println("The average is " + average); or System.out.printf("The average is %f ", average);
If you want the average of numbers, you cannot divide an integer total by an integer count because the result will be an integer, which does not account for decimal points.
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int positive = 0, negative = 0, total = 0, count = 0;
double average;
System.out.println("Enter the number: ");
int number;
while ((number = input.nextInt()) != 0) {
total += number;
count++;
if (number > 0) {
positive++;
} else if (number < 0) {
negative++;
}
}
average = (double) total / count;
System.out.println("The number of positives is " + positive);
System.out.println("The number of negatives is " + negative);
System.out.println("The total is " + total);
System.out.printf("The average is: " + average);
}
}
Also, you don't have to use %d in your line System.out.printf("The average is %d", average);
You can write System.out.printf("The average is: " + average); because when you print out a String, anything concatenated within the parentheses will also be converted to a String, and printed out as such
Simply multiply your int variable by 1.0 to convert it into floating point variable
average=1.0*total/count;
This should do.
And you can use following statement to display the value
System.out.println("The average of numbers is "+average);
// Scanner is in java.util package
import java.util.Scanner;
class CountPandN
{
public static void main(String args[])
{
// create a Scanner object
Scanner input = new Scanner(System.in);
// prompt user to enter numbers
System.out.println("Enter + and - numbers");
System.out.println("Enter 0 when you're finished");
// initialize the variables
int n, countP, countN, count;
n = input.nextInt();
countP = 0;
countN = 0;
count = 0;
int sum = n;
float average = (float) sum / 2;
while (n != 0)
{
n = input.nextInt();
count++;
if(n >= 0)
countP++;
if (n < 0)
countN++;
}
System.out.println("Total positive " + countP);
System.out.println("Total negative " + countN);
System.out.println("Total numbers " + count);
System.out.println("Total average " + average);
}
}
if you simply change System.out.printf("The average is %d ", average); with System.out.printf("The average is " +average); i.e. if you remove%d and use '+'instead ',' then it will work for you, and also to get answer in float you need to use typecasting. i.e. add (double) in average = (double)total / count;

How to use Java to calculate average from input?

I need a program that should add x numbers. The numbers should come from user input so I need some sort of loop. I have gotten as far as shown below, but I'm stuck since I have no idea how to add a new number without deleting the previous?
System.out.println("How many numbers to use?");
int number = keyboard.nextInt();
for (int i = 0; i<number ; i++) {
System.out.println("whats the number");
double first = keyboard.nextDouble();
}
If all you need is the average, you don't need to keep all the numbers you get from user input. Just keep one variable that holds their sum.
define the sum variable outside the loop (initialized to 0), and add to it each number you get from user input.
int number = keyboard.nextInt();
double sum = 0;
for (int i = 0; i<number ; i++)
{
System.out.println("whats the number");
sum += keyboard.nextDouble();
}
double average = sum / number;
public class Average {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double sum = 0;
int num;
System.out.println("enter how many num");
num = sc.nextInt();
System.out.println("please enter " + num + " numbers");
for (int i = 0; i < num; i++) {
sum += sc.nextDouble();
}
double avg = sum / num;
System.out.println("Average of " + num + " numbers is:" + avg);
}
}

Categories