How to use Java to calculate average from input? - java

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

Related

Print out Average in for loop

This is my question
get to input a positive integer representing a number of weeks, loop
continuously until the value entered is positive. For each week, enter
a value for liters and a value for kilometers. For each value, should
loop until the value entered is positive. both values is a real
number. Then output the fuel economy for that week (liters divided by
kilometers). Finally, output the average fuel economy. You must make
good use of submodules in your answer.
This is my work
import java.util.*;
public class Exam8 {
public static void main(String[] args) {
int numweek = 0;
double valkms = 0;
double vallits = 0;
double average = 0;
double result = 0;
int count = 0;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of week: ");
numweek = sc.nextInt();
while (numweek < 1) {
System.out.println("Enter a positive of number week: ");
numweek = sc.nextInt();
}
while (true) {
count++;
System.out.print("Enter value of litres: : ");
vallits = sc.nextDouble();
while (vallits < 0) {
System.out.print("Positive litres: ");
vallits= sc.nextDouble();
}
System.out.print("Enter value of kilometres: : ");
valkms = sc.nextDouble();
while (valkms < 0) {
System.out.print("Positive kilometres: ");
valkms = sc.nextDouble();
}
if (vallits == 0 || valkms == 0) {
break;
}
result = vallits / valkms;
sum = result + (double)count;
System.out.println(result);
}
//average = getAverg(sum,count);
System.out.print("Average of fuel economy is: " + average);
}
public static double getAverg(double sum, int count) {
double average;
average = sum/count;
return average;
}
}
I get a problem when input value of lit and km, for example, I like to stop when to put either of a value of lit or km. Then I have another problem with outputting an average of the result (lit/km).
This code should work:
import java.util.*;
public class App {
public static void main(String[] args) {
int numweek = 0;
double valkms = 0;
double vallits = 0;
double average = 0;
double result = 0;
int count = 0;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of week: ");
numweek = sc.nextInt();
while (numweek < 1) {
System.out.println("Enter a positive of number week: ");
numweek = sc.nextInt();
}
while (count < numweek) {
count++;
System.out.print("Enter value of litres: : ");
vallits = sc.nextDouble();
while (vallits < 0) {
System.out.print("Positive litres: ");
vallits= sc.nextDouble();
}
System.out.print("Enter value of kilometres: : ");
valkms = sc.nextDouble();
while (valkms < 0) {
System.out.print("Positive kilometres: ");
valkms = sc.nextDouble();
}
if (vallits == 0 || valkms == 0) {
break;
}
result = vallits / valkms;
sum += result;
System.out.println(result);
}
System.out.print("Average of fuel economy is: " + getAverg(sum, numweek));
}
public static double getAverg(double sum, double numOfWeeks) {
double average;
average = sum/numOfWeeks;
return average;
}
}
Your first error was that the condition in the while loop wasn't correct. In order for the loop to stop you need to specify proper conditions. If condition is true it will loop indefinetely or until you set break.
Your second error was that you didn't calculate the average correctly. You should have just taken the sum for every week and added it to the current sum(which is zero at the beggining), and then just divide that sum by number of weeks to get the average.
You also didn't use your getAverg function anywhere.

Calculate Average in arrays

I want to calculate the average numbers using arrays. I want the program asks for the amount of grades and after I want to put the grade numbers.
After I want to get the average output in a double.
This is my code so far:
public class Average {
public static void main(String[] args)
{
//int n = MyConsole.readInt("Enter number of grades: " );
int a = MyConsole.readInt("Enter grade 1: " );
int b = MyConsole.readInt("Enter grade 2: " );
int c = MyConsole.readInt("Enter grade 3: " );
int[] numbers = new int[]{a,b,c};
numbers[0] = a;
numbers[1] = b;
numbers[2] = c;
int sum = 0;
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
double average = sum / numbers.length;
System.out.println("Average value of array elements is : " + average);
}
}
Don't know what your class MyConsole is doing, but I guess is a Scanner:
Your code improved will be something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of grades: " );
int n = sc.nextInt();
int sum = 0;
for (int i = 0; i < n; i++) {
System.out.print("Enter grade "+ (i + 1) + ": ");
int a = sc.nextInt();
sum += a;
}
double average = sum / n;
System.out.println("Average value of array elements is : " + average);
}
OUTPUT (2 grades):
Enter number of grades: 2
Enter grade 1: 1
Enter grade 2: 5
Average value of array elements is : 3.0
OUTPUT (5 grades):
Enter number of grades: 5
Enter grade 1: 10
Enter grade 2: 20
Enter grade 3: 30
Enter grade 4: 10
Enter grade 5: 50
Average value of array elements is : 24.0
NOTE
double average = sum / n;
performs an int division, so you won't have any decimal places! I would propose a fast cast:
double average = sum / (double) n;
With new output:
Enter number of grades: 2
Enter grade 1: 1
Enter grade 2: 4
Average value of array elements is : 2.5
GUESS using your own class:
public static void main(String[] args) {
int sum = 0;
int n = MyConsole.readInt("Enter number of grades: " );
for (int i = 0; i < n; i++) {
int a = MyConsole.readInt("Enter grade "+ (i + 1) + ": ");
sum += a;
}
double average = sum / n;
System.out.println("Average value of array elements is : " + average);
thank you !
Sorry for the poor explanation.
This is my first question
this it the code after edit:
import java.util.Scanner;
public class Average {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of grades: ");
int n = sc.nextInt();
int sum = 0;
int[] numbers = new int[n];
for(int i=0; i < numbers.length ; i++)
{
System.out.println("Enter grade " + (i + 1) + " :");
int a = sc.nextInt();
sum = sum + a;
}
double average = sum / (double) n;
System.out.println("Average value of array elements is : " + average);
sc.close();
}
}
Program to Calculate Average Using Arrays:
public class Inter1 { //name of the class
public static void main(String[] args) {//main method
int number[]={40,56,23,56,87,23,78}; //declaring the int array
int sum=0;
for (int s:number){ //for each
sum +=s;
}
int ave=sum/number.length; //to get the average
System.out.println("the average is "+ave); //out put
}
}
package inter1;
import static java.time.Clock.system;
import java.util.Scanner;
public class Inter1 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int total=0;
System.out.println("Enter how many number that do u wanna enter ?? ");
int num= in.nextInt();
int numbers[]=new int[num];
for (int i=0;i<numbers.length;i++){
System.out.println(i+1+":"+"enter the your numbers ? ");
numbers[i]=in.nextInt();
}
for (int i=0;i<numbers.length;i++){
total+=numbers[i];
}
int average =total/numbers.length;
System.out.println("the average is "+average);
}
}
public class Inter1 { //name of the class
public static void main(String[] args) { //main method
System.out.println("==============================");
int num[]={34,56,78,78,34,2,33,99,100,56}; //int array
int total=0;
for (int i=0;i<num.length;i++){ //for loop
total+=num[i];
}
int avrage1=total/num.length; //output
System.out.println("The average is "+avrage1);
}
}

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.

Determine the highest and lowest number

I'm currently writing a program where the user must input 10 numbers and then the output will be the highest number and the lowest number. There is something wrong in my code but couldn't find it.
int highest=0, lowest=0, num=0;
Scanner scan = new Scanner(System.in);
for (int i=0; i<10; i++) {
System.out.print("Enter a number:");
num = scan.nextInt();
}
if (num > highest) {
highest = num;
}
else if(num < lowest) {
lowest = num;
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
Initialise your values differently:
int highest = Integer.MIN_VALUE;
int lowest = Integer.MAX_VALUE;
If you initialise them both to zero, you will never have a "highest" value below zero, or a "lowest" value above zero
You should put your two if conditions in the for loop else you will only compare the last number. And lowest shouldn't be set to 0 but to Integer.MAX_VALUE
You have some issues with your initialization and your logic:
int highest=Math.MIN_VALUE;
int lowest=Math.MAX_VALUE;
int num=0;
Scanner scan = new Scanner(System.in);
for(int i=0; i<10; i++){
System.out.print("Enter a number:");
num = scan.nextInt();
if (num > highest){
highest = num;
}
if(num < lowest){
lowest = num;
}
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
You should also use 2 if conditions rather than an else if. If you have only one number, chances are that you will end up with something similar to highest being equal to some digit you entered while lowest will still be equal to Math.MAX_VALUE. This can cause confusion.
You are implicitly assuming that lowest and largest are 0, that might now be the case,
try this code snippet..
class Main{
public static void main(String args[]){
int highest=0, lowest=0, num=0;
Scanner scan = new Scanner(System.in);
highest = lowest = scan.nextInt();
for(int i=1; i<10; i++){
System.out.print("Enter a number:");
num = scan.nextInt();
if (num > highest){
highest = num;
}
if(num < lowest){
lowest = num;
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
}
}
}

Categories