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);
}
}
Related
I'm creating a program to find the average of all the numbers entered by the user and storing those numbers to check whether the number entered falls below or above the average that was calculated.
My program outputs all numbers entered as below average. i have check on stack overflow for similar problems i have tried all that but my output still displays below the average only
This is what i have tried
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
//The loop for calculating the average
for (int i = 1; i <= 5; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
double aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <=5; j++)
{
if(aboveAvg > avg)
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
}
This is a possible solution for your problem:
Note that you need to store the user inputs, calculate the average once (not inside the for loop), and finally compare the numbers stored with the average calculated before.
public void newspaper() {
Scanner in = new Scanner(System.in);
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int[] youths = new int[5];
// The loop for calculating the average
for (int i = 0; i < youths.length; i++) {
System.out.println("Youth " + (i + 1) + " How many was delivered?");
youths[i] = in.nextInt();
sum = sum + youths[i];
}
// Note that the average can be calculated once, not every iteration
avg = sum / youths.length;
System.out.println("Average is: " + avg + "\n");
// The loop for checking below of above average
for (int i = 0; i < youths.length; i++) {
if (youths[i] > avg) {
System.out.println("Youth " + (i + 1) + " is above average");
} else {
System.out.println("Youth " + (i + 1) + " below average");
}
}
}
Try to use array instead of variable
see below code
import java.util.Scanner;
public class Stackoverflow {
public void newspaper() {
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int numYouth = 5;
int youth[] = new int[numYouth];
Scanner sc = new Scanner(System.in);
// The loop for calculating the average
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + i + " How many was delivered?");
youth[i] = sc.nextInt();
sum = sum + youth[i];
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
double aboveAvg = 0;
// The loop for checking below of above average
for (int j = 0; j < 5; j++) {
if (youth[j] > avg) {
System.out.println("Youth " + j + " is above average");
} else {
System.out.println("Youth " + j + " below average");
}
}
}
public static void main(String[] args) {
new Stackoverflow().newspaper();
}
}
You need to store the numbers in a temporary list and use counter 'ctr' for incrementing the values of the matched case. I have used for each loop for simplicity.
public void newspaper() {
System.out.println("Question 4 \n");
int youth;
double avg = 0;
int sum = 0;
int numYouth = 5;
List<Integer> number = new ArrayList<>();
// The loop for calculating the average
int ctr = 0;
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + ++ctr + " How many was delivered?");
youth = in.nextInt();
number.add(youth);
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
ctr = 0;
// The loop for checking below of above average
for (int j : number) {
if (j > avg) {
System.out.println("Youth " + ++ctr + " is above average");
} else {
System.out.println("Youth " + ++ctr + " below average");
}
}
}
Assuming that you're trying to 'find the average of all the numbers entered by the user, storing those numbers to check whether each of the numbers entered falls below or above the average that was calculated', below are the things you need to fix:
The "storing those numbers" part
Compare the calculated average against the stored number.
A possible solution:
Use a list or an array to store the numbers entered by the user.
You can use an array as long as you know the number of elements to store before starting to read the numbers.
Read values from the list/array when you want to compare the entered value with the calculated average.
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
// Create a list to store the entered values
// List<Integer> enteredNumbers = new ArrayList<Integer>();
// Using an array of '5' elements - this 5 comes from numYouth
int[] enteredNumbers = new int[numYouth]; // better not to 'hardcode'
//The loop for calculating the average
for (int i = 1; i <= numYouth; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
enteredNumbers[i-1] = youth; // array is 0-indexed
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
// an int is enough to track the number of values above the average
int aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <= numYouth; j++)
{
// compare stored value against the average calculated above
if(enteredNumbers[j-1] > avg) // array is 0-indexed
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
System.out.println(aboveAvg + " Youths are above average");
}
What did I do wrong? I'm really not sure what else to try or where my mistake is. Thanks for any help. It's supposed to calculate the sum of integers between two numbers, e.g. between 3 and 6 it would be 3 + 4 + 5 + 6
import java.util.Scanner;
public class TheSumBetweenTwoNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("First:");
int n = Integer.parseInt(reader.nextLine());
System.out.println("Second:");
int max = Integer.parseInt(reader.nextLine());
int sum = 0;
int i = 0;
int difference = max - n;
while (i < difference) {
sum = n + (n + 1);
n++;
i++;
}
System.out.println("Sum is " + sum);
}
}
Why all this you need just a piece of code like this :
public static void main(String args[]) {
int min = 3, max = 6, sum = 0;
for (int i = min; i <= max; i++) {
sum += i;
}
System.out.println(sum);
}
With while loop it should be :
...
int i = min;
while (i <= max) {
sum += i;
i++;
}
...
You don't need to find a difference and loop over it, just running a loop from n to max will do. Also, you need to add the value to sum (+=) instead of assigning a value to it (=, which overwrites previous value)
Try this:
int i = n;
while (i <= max) {
sum += i;
i++;
}
You're overwriting the previous sum value with the most recent n + (n + 1), instead of accumulating the previous sum. Also, your loop is one iteration short. Try this:
int sum = 0;
for (int i = n; i <= max; i++) {
sum += i;
}
System.out.println("Sum is " + sum);
Change this snippet
int sum = 0;
int i = 0;
int difference = max - n;
while (i < difference) {
sum = n + (n + 1);
n++;
i++;
}
In
int sum = 0;
int i = n;
while (i <= max) {
sum = sum + i;
i++;
}
You made it a little bit overcomplicated. All you really need is a for loop that runs from n to max that adds up the incrementing variables:
int sum = 0;
for(int i = n; i <= max; i++){
sum += i;
}
I am supposed to create a perfect number class using the following pseudocode:
For i from 2 to “very large”,
For j from 2 to √i,
if (j evenly divides i),
accumulate the sum j and i/j
if √i is an integer
subtract √i ... you added it twice
if the sum of divisors == i
Print the number ... it’s perfect!
So here is my version. It runs, but it doesn't do what I want at all. It just runs and produces nothing as an output. Can someone tell me what is wrong with my program? It's bothering me so much.
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) {
double sum = 0
double newsum = 0;
for (int i = 2; i < 1000000; i++) {
for (int j = 2; i<Math.sqrt(i); j++){
if (i%j==0){
sum = j + (i%j);
}
if (Math.sqrt(i)==(int)i){
newsum = sum - Math.sqrt(i);
}
if (sum == 0) {
System.out.println(sum + "is a perfect number");
}
}
}
}
}
Few mistakes according to the algorithm:
sum = j + (i%j); should be changed to sum = j + (i/j);
This piece:
if (Math.sqrt(i)==(int)i){
newsum = sum - Math.sqrt(i);
}
if (sum == 0) {
System.out.println(sum + "is a prime number");
}
Should be under upper "for"
Math.sqrt(i)==(int)i would never be true unless i is 1. If you want to check this that way you should write Math.sqrt(i)==((int) Math.sqrt(i))
There are much more errors, the simplest way to do it is:
double sum = 0;
for (int i = 1; i <= 10000; i++) {
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
if (i == sum) {
System.out.println(sum + " is a prime number");
}
sum = 0;
}
Your code contains several mistakes. Here is the corrected code, commented with the changes.
// newsum isn't needed; declare sum to be int to avoid floating-point errors
int sum = 0;
for (int i = 2; i < 1000000; i++) {
// Start with 1; every natural number has 1 as a factor.
sum = 1;
// Test if j, not i, is less than the square root of i.
for (int j = 2; j <= Math.sqrt(i); j++){
if (i % j == 0){
// Add to sum; don't replace sum. Use i / j instead of i % j.
sum = sum + j + (i / j);
// Move test inside this if; test if j is square root of i
if (j*j == i){
// I used j because we know it's the square root already.
sum = sum - j;
}
}
// Move print outside of inner for loop to prevent multiple
// printings of a number.
// Test if sum equals the number being tested, not 0.
if (sum == i) {
// Space before is
System.out.println(sum + " is a perfect number");
}
}
}
Output:
6 is a perfect number
28 is a perfect number
496 is a perfect number
8128 is a perfect number
public static void main(String[] args){
int min = 2;
int max = 1000000;
int sum = 0;
for (; min <= max; min++,sum = 0) {
for (int e = 1; e < min; e++)
sum += ((min % e) == 0) ? e : 0;
if (sum == min){
System.out.println(sum);
}
}
}
for(n=1;n<=number;n++){ //calculates the sum of the number.
int i=1;
int sum = 0;
while(i<n){
if(n%i==0)
sum+=i;
i++;
}
if(sum==n){ //if the sum is equal to its sum :
System.out.print(n+": ");
for (int j = 1;j<n;j++){
if(n%j==0){
System.out.print(j+" ");
}
}
System.out.println();
}
}
Here is the simplest and easiest form you can write a program for perfect number....this code gives perfect number within 25 ...you can change as you want
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) {
int n,i,j,count=0;
for(i=2;i<=25;i++) {
for(j=1;j<=i;j++) {
if(i%j ==0) /*count increments if a reminder zero*/ {
count++;
}
}
/*since a perfect number is divided only by 1 and itself
if the count is 2 then its a prime number...*/
if(count==2)
System.out.println(i);
count=0;
}
return 0;
}
}
According to the pseudocode you want to move the second and third if test outside of the inner loop
for (int i = 2; i < 1000000; i++) {
double iroot = Math.sqrt(i);
int sum = 1;
for (int j = 2; j <= iroot; j++){
if (i % j == 0){
sum = sum + j + i / j;
}
}
if (iroot == (int) iroot) {
sum = sum - iroot;
}
if (sum == i) {
System.out.println(sum + "is a perfect number");
}
}
Thanks for watched
public boolean testPerfect(int n){
int i=1;
int sum=0;
while(i<n){
if(n%i==0)
{
sum+=i++;
}
else{
i++;}
}
if (sum==n){
return true;
}
return false;
}
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);
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;