Java, averaging a list of numbers - java

In the following Java code, my average temperature is 1 decimal place off.
For example Instead of being 69.0 it's 6.9.
The input can be any 10 numbers. So lets say I input 10 temperatures and each 1 is 10 degrees. The total for the 10 inputs is 100, so the average should be 10 but instead I'm receiving an average of 1.0.
Code:
import java.util.Scanner;
public class NumberAboveAverage {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int TotalTemps = 10;
double[] numbers = new double[TotalTemps];
double sum = 0;
double average = 0;
double max = 0;
for (int n = 0; n < numbers.length; n++) {
System.out.print("Enter a temperature: ");
numbers[n] = input.nextInt();
if (numbers[n] > max) {
max = numbers[n];
}
sum = numbers[n];
}
for (int i = 0; i < numbers.length; i++) {
sum = numbers[i];
}
average = sum / 10; //average is not an average of the numbers.
System.out.println("Average temp = " + average);
int count = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] > average) {
count++;
}
}
System.out.println(count + " days were above average");
}
}

You're not actually summing the numbers together.
It should be sum += numbers[i];
not sum = numbers[i];
You also appear to be attempting to do this twice, which is unnecessary.

You are missing a +
sum = numbers[n];
needs to be
sum += numbers[n];
This does nothing,
for (int i = 0; i < numbers.length; i++) {
sum = numbers[i];
}

You sum twice (second for-loop) and do it wrongly with: sum = numbers[n]; instead of: sum += numbers[n];
You should change your code to:
...
for (int n = 0; n < numbers.length; n++) {
System.out.print("Enter a temperature: ");
numbers[n] = input.nextInt();
if (numbers[n] > max) {
max = numbers[n];
}
sum += numbers[n];
}
// SECOND FOR LOOP REMOVED !!!
average = sum / 10;
System.out.println("Average temp = " + average);
...

Replace
average = sum / 10;
with
average = sum / 10.0;

Related

Java program won't print out the smallest number in an array

I'm trying to find the largest and smallest number in my array however, it only seems to print out the largest and not the smallest, I'm fairly new so all help is appreciated, thank you.
import java.util.Scanner;
public class Ex1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[11];
int largest = numbers[0];
int smallest = numbers[0];
System.out.println("Enter 10 numbers = ");
for (int i = 1; i < numbers.length; i++) {
numbers[i] = keyboard.nextInt();
System.out.println("Number " + i + " = " + numbers[i]);
for (int y = 1; y < numbers.length; y++) {
if (numbers[y] > largest)
{
largest = numbers[y];
}
}
for (int x = 1; x < numbers.length; x++)
{
if (numbers[x] < smallest)
{
smallest = numbers[x];
}
}
}
System.out.println("Largest number = " + largest);
System.out.println("Smallest number = " + smallest);
} // main
} // class
It doesn't print out the smallest number because you set it in the beginning to 0, set it to Integer.MAX_VALUE instead.
Also to make sure your program works for negative numbers, set the value of largest to Integer.MIN_VALUE.
int smallest = numbers[0];
This is creating problem. This assigns value 0 in the beginning hence you are not getting smallest number.
Also your test dataset must be containing only positive numbers.
Solution
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
There are some code issues other than correctly finding min and max of input numbers.
You don't have to write nested for loops for this. Check below code and that will simply find you min and max numbers,
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[11];
int largest = numbers[0];
int smallest = numbers[0];
System.out.println("Enter 10 numbers = ");
for (int i = 1; i < numbers.length; i++) {
numbers[i] = keyboard.nextInt();
System.out.println("Number " + i + " = " + numbers[i]);
if (i == 1) {
largest = numbers[i];
smallest = numbers[i];
}
if (numbers[i] > largest) {
largest = numbers[i];
}
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
System.out.println("Largest number = " + largest);
System.out.println("Smallest number = " + smallest);
try this,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter 10 numbers = ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = keyboard.nextInt();
System.out.println("Number " + (i + 1) + " = " + numbers[i]);
}
int largest = numbers[0];
int smallest = numbers[0];
for (int y = 0; y < numbers.length; y++) {
if (numbers[y] >= largest)
{
largest = numbers[y];
}
if (numbers[y] <= smallest)
{
smallest = numbers[y];
}
}
System.out.println("Largest number = " + largest);
System.out.println("Smallest number = " + smallest);
}

Average of Rnd Num in a loop java

I'm stuck trying to calculate the average when I generate 3 random integers between 1 and 20. I have to round the average to int and repeat it 10000 times. When I test my program repeating 2 times, I am getting the output of:
Number is :18
Number is :14
Number is :2
sum is: 34
Average is: 11
Number is :13
Number is :3
Number is :6
sum is: 56
Average is: 18
However, the average should be the average of just the 3 numbers. Here, the second loop adds the sum of the first loop to the sum of the second making the average wrong (Sum:34+22=56). I want it to be 22 so the average for that would be 7. I notice the problem might be this line, sum += n; , but I don't know another way to add the 3 number for each loop to get the average.
package Histogram;
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
final int N = 2;
Random rand = new Random();
int n;
int average;
int sum = 0;
for (int a = 0; a < N; a++) {
for (int i = 0; i < 3; i++) {
n = rand.nextInt(20) + 1;
System.out.println("Number is :" + n);
sum += n;
}
average = sum / 3;
System.out.println("sum is: " + sum);
System.out.println("Average is: " + average);
}
}
}
Your sum += n; inside the second for loop keeps on incrementing the value of sum (even the older sum values from loop). Thus you need to reset the value of sum to 0 every time at the begineeing the first loop.
for (int a = 0; a < N; a++) {
sum = 0;
//rest of the code
You must clean the sum variable after the first loop:
//..
int sum;
for (int a = 0; a < N; a++) {
sum = 0; // -------> Here it is necessary to be clean for the next iteration
for (int i = 0; i < 3; i++) {
n = rand.nextInt(20) + 1;
System.out.println("Number is :" + n);
sum += n;
}
//...
}
the average should be the average of just the 3 numbers. Here, the
second loop adds the sum of the first loop to the sum of the second
making the average wrong (Sum:34+22=56). I want it to be 22 so the
average for that would be 7
One approach is to reset the value of sum after you've printed the sum and average to the console.
Example:
int n;
int average;
int sum = 0;
for (int a = 0; a < N; a++) {
for (int i = 0; i < 3; i++) {
n = rand.nextInt(20) + 1;
System.out.println("Number is :" + n);
sum += n;
}
average = sum / 3;
System.out.println("sum is: " + sum);
System.out.println("Average is: " + average);
sum = 0;
}
or to make life easier you can make the variable sum local within the loop so that at each iteration the value of sum will reset to default value:
Example:
int n;
int average = 0;
for (int a = 0; a < N; a++) {
int sum = 0;
for (int i = 0; i < 3; i++) {
n = rand.nextInt(20) + 1;
System.out.println("Number is :" + n);
sum += n;
}
average = sum / 3;
System.out.println("sum is: " + sum);
System.out.println("Average is: " + average);
}
If you want the total sum I suggest adding a second iterationSum variable to add up the 3 numbers. Something like:
for (int a = 0; a < N; a++) {
int iterationSum = 0;
for (int i = 0; i < 3; i++) {
...
iterationSum += n;
}
average = iterationSum / 3;
...
}
If you don't care about the total sum just reset you sum to 0 in each iteration:
for (int a = 0; a < N; a++) {
sum = 0;
...
}
public static void main(String[] args) {
final int N = 2;
Random rand = new Random();
int n;
int average;
int sum = 0;
for (int a = 0; a < N; a++) {
sum=0;// this makes the trick
for (int i = 0; i < 3; i++) {
n = rand.nextInt(20) + 1;
System.out.println("Number is :" + n);
sum += n;
}
average = sum / 3;
System.out.println("sum is: " + sum);
System.out.println("Average is: " + average);
}
}

print only the numbers that the user entered and is strictly less than average

So now the average is calculated, I am trying to print out the user input ,in its own line only which are strictly less than the average. I tried doing this but, go an error"bad operands for binary operator "<" .
import java.util.Scanner;
public class avg
{
public static void main (String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter some numbers(Ctrl-d to quit):");
double[] myArray = new double[10];
int howMany = 0;
double sum=0 ;
double avg=0;
while (in.hasNextDouble()) // Ctrl-D to terminate
{
double userVal = in.nextDouble();
myArray[howMany++] = userVal;
if ( howMany >= myArray.length )
{
//myArray.length = myArray.length * 2;
double[] tempArray = new double[2 * myArray.length];
for (int i = 0; i < howMany; i++)
tempArray[i] = myArray[i];
myArray = tempArray;
}
}
for (int i = howMany - 1; i >= 0; i--)
{
sum += myArray[i];
}
avg = sum/howMany;
System.out.print("Average: "+ avg);
System.out.println(myArray<avg);// to print numbers that the user entered only which are strictly less than the avg. This did not work//
}
}
for (int i = howMany - 1; i >= 0; i--){
sum+=myArray[i];//sum up the array
}
avg = sum / howMany;
To print each double in one line:
System.out.println(avg);
for (int i = 0; i < howMany; i++) {
if(myArray[i] < avg){
System.out.println(myArray[i]);//single line for every double
}
}
print all doubles in one line:
String oneLine = "[";
int lowerAvg = 0;
for (int i = 0; i < howMany; i++) {
if(myArray[i] < avg){
oneLine += (i > 0 && ++lowerAvg > 0)?", ":""; // add separator
oneLine += (myArray[i]);
}
}
oneLine+="]";
System.out.println(oneLine);//prints like [1.0, 2.0, ...]
Using Java 8:
avg = Arrays.stream(myArray, 0, howMany).average().orElse(0);
final double finalAvg = avg;//final variable to use in filter condition
System.out.println(finalAvg);
Arrays.stream(myArray, 0, howMany).filter(x -> x < finalAvg).forEach(System.out::println);//will print every double in a single line
System.out.println(Arrays.toString(Arrays.stream(myArray, 0, howMany).filter(x -> x < finalAvg).toArray()));//Will print the array like [1.0, 2.0, ...]

Enter 10 values and summing up all the values in a Java Array

I am just starting out with arrays and can't figure out why my code is wrong. It should let the user enter 10 values and then display the sum.
Here is my code:
//This program let the user enter 10 values and sums them up
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
for (int i = 0; i < myArray.length; i++) {
myArray[i] = input.nextInt();
System.out.println("The values are " + myArray[i]);
for (i = 0; i < myArray.length; i++) {
int sum = 0;
sum += myArray[i];
System.out.println("The sum of the values is:" + sum);
}
}
}
}
Thank you for your support
Your problem comes from your loops (they should be one after the other), and how you initialize your variable sum (it should be initialized outside the loop).
Your code should rather be something like this:
Scanner input = new Scanner(System.in);
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
for (int i = 0; i < myArray.length; i++) {
myArray[i] = input.nextInt();
System.out.println("The values are " + myArray[i]);
}
int sum = 0;
for (int i = 0; i < myArray.length; i++) {
sum += myArray[i];
}
System.out.println("The sum of the values is:" + sum);
Or with only one loop
Scanner input = new Scanner(System.in);
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
int sum = 0;
for (int i = 0; i < myArray.length; i++) {
myArray[i] = input.nextInt();
System.out.println("The values are " + myArray[i]);
sum += myArray[i];
}
System.out.println("The sum of the values is:" + sum);
Here is the correct code for your problem:
You have enclosed summing up values inside the
input for loop
.
You should also define int sum=0; separately outside the second for loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
for (int i = 0; i < myArray.length; i++) {//open here
myArray[i] = input.nextInt();
System.out.println("The values are " + myArray[i]);
}//close here. you will input values inside this loop
int sum = 0;//if you have to initialize sum only once, if you put it inside for loop sum wil be zero after every iteration in the loop
for (int i = 0; i < myArray.length; i++) {//here you add up all values
sum += myArray[i];
System.out.println("The sum of the values is:" + sum);
}
}
Be careful, you are doing loops inside other loops.
Every thing you do in a loop is repeated as many times as the loops number.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
// Read the value from the user
for (int i = 0; i < myArray.length; i++) {
myArray[i] = input.nextInt();
}
// display values
System.out.println("The values are ");
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
// Do sum
// Sum start at 0 outside the loop and then we are going to add every number
int sum = 0;
for (i = 0; i < myArray.length; i++) {
sum += myArray[i];
}
System.out.println("The sum of the values is:" + sum);
}
}
i want to say that you init 10 double array but you give the value with int,it can happen error and the blew the sum is also int.
I suggest it like this.
Here you have to provide exactly 10 numbers to get the sum.
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
int sum = 0;
for (int i = 0; i < 10; i++) {
Scanner input = new Scanner(System.in);
if(input.hasNextInt()){
myArray[i] = input.nextInt();
System.out.println("The values are " + myArray[i]);
sum += myArray[i];
}else{
System.out.println("Not a value.");
i--;
}
input = null;
}
System.out.println("The sum of the values is:" + sum);

Java Application of Arrays and For-loop

Here's the question:
Write a program that that reads ten integers into an array and
computes the sum of the array of values, except for the largest one.
(Hint: Find the difference between the sum and the largest value of the
array)
And this is the given sample that you have to achieve:
Please input 10 integers: 3 4 1 9 2 10 8 6 7 5
Sum without the max: 45
The program beneath is my personal attempt:
import java.util.Scanner;
public class SumWithoutMax {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Please input 10 integers: ");
int [] x = new int [10];
for (int i = 0; i < x.length; i++) {
x[i] = in.nextInt();
}
int max = x[0];
int sum = 0-max;
for (int i = 0; i < x.length; i++) {
if(x[i] > max) {
max = x[i];
}
}
for (int i = 0; i < x.length; i++) {
sum = sum + x[i];
}
System.out.println("Sum without the max: " +sum);
}
}
And the result of my attempt is just like this:
Please input 10 integers: 3 4 1 9 2 10 8 6 7 5
Sum without the max: 52
What's wrong with the program actually? Can somebody help me find it out and teach me how to solve it? Thanks:)
Problem with your code is you are subtrating x[0] value (which assume max at initial).
Even You can achive the with single for-loop.
int max = x[0];
int sum = 0;
for (int i = 0; i < x.length; i++) {
if(x[i] > max) {
max = x[i];
}
sum = sum + x[i];
}
sum -=max;
You are subtracting the maximum before you know it. Move int sum = 0-max; after the loop that seeks it.
The first sum=0-max; is wrong because max is not known yet. You need to do it after you find the max.
for (int i = 0; i < x.length; i++) {
sum = sum + x[i];
}
sum -= max;
int sum = -max;
When loop find the maximum number.
Move this line:
int sum = -max;
after the loop that finds the max.
import java.util.Scanner;
public class SumWithoutMax {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Please input 10 integers: ");
int [] x = new int [10];
for (int i = 0; i < x.length; i++) {
x[i] = in.nextInt();
}
int max = x[0];
int sum = 0;
for (int i = 0; i < x.length; i++) {
if(x[i] > max) {
max = x[i];
}
}
for (int i = 0; i < x.length; i++) {
sum = sum + x[i];
}
sum = sum - max;
System.out.println("Sum without the max: " +sum);
}
}
A possible answer in JAVA 8 :
Integer sum = Arrays.asList(3,4,1,9,2,10,8,6,7,5).stream().sorted(Comparator.reverseOrder()).skip(1).reduce(
0,(a, b) -> a + b);

Categories

Resources