Java sum of numbers error - java

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

Related

Mooc.fi Exercise: Average of positive numbers fail

I've spent all day but couldn't find a solution. Could someone please help and tell me what the error is? 75% of the code is correct, mooc says. But it fails because:
Fail: When input was: 0, output shouldn't contain: 0.
In other words, when I input 0 alone, it calculates the average of that one 0. However, the exercise calls for all non-positive numbers to be excluded from the average calculation.
This contradictory output is what I get when I enter a zero:
Give a number:
0
Cannot calculate the average
Average of the numbers: 0.0
Here is my code. I'm a beginner in Java and perhaps you guys can see something I can't. All help much appreciated
import java.util.Scanner;
public class AverageOfPositiveNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberofinputs = 0;
double sumofinputs = 0;
double average = 0;
double negative = 0;
double positive = 0;
// For repeatedly asking for numbers
while (true) {
System.out.println("Give a number: ");
// For reading user input
int numberFromUser = Integer.valueOf(scanner.nextLine());
if (numberFromUser <= 0) {
negative = numberFromUser;
} else {
positive = numberFromUser;
}
if (positive == 0){
System.out.println("Cannot calculate the average");
}
if (numberFromUser == 0){
break;
}
if (positive == numberFromUser){
numberofinputs = numberofinputs + 1;
sumofinputs = (sumofinputs + positive);
average = (double) sumofinputs/numberofinputs;
}
}
System.out.println("Average of the numbers: " + average);
}
}

How to fix getting an average from user input

The instructions are the following:
Write a method called inputThenPrintSumAndAverage that does not have any parameters.
The method should not return anything (void) and it needs to keep reading int numbers from the keyboard.
When the user enters something that is not an int then it needs to print a message in the format "SUM = XX AVG = YY". XX represents the sum of all entered numbers of type int.
YY represents the calculated average of all numbers of type long.
I've coded the following method but I keep getting the incorrect average. What can I change to get the correct average?
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
int sum = 0, counter = 0;
long average = 0L;
while(true) {
boolean number = scanner.hasNextInt();
if(!number)
{
counter++;
break;
}
else {
int digit = scanner.nextInt();
sum += digit;
counter++;
}
}
average = sum / counter;
System.out.println("SUM = " + sum + " AVG = " + average);
}
The following should do:
if(!number)
break;
Your average is wrong because you are incrementing "counter" more than you should.
Of course in the end you are going to have to add one more if statement to make sure you are not attempting to divide by counter if the counter is zero. In that case, an average is undefined.
Also, as others have pointed out in the comments, it is entirely unclear to us what you mean when you say "I keep getting the incorrect average", and we generally frown upon questions worded so vaguely. But if by any chance a "correct average" for you means an average with decimals, then you should use a double instead of a long for your average, and you should cast your counter to double before dividing, so as to force a double division instead of a long division.
Use scanner.hasNextInt() to read util a non-integer value is supplied as input:
public static void inputThenPrintSumAndAverage() {
Scanner scanner = new Scanner(System.in);
int number, sum = 0, counter = 0;
long average = 0L;
while (scanner.hasNextInt()) {
number = scanner.nextInt();
sum += number;
counter++;
}
if(counter != 0){
average = sum / counter;
}
System.out.println("SUM = " + sum + " AVG = " + average);
}
Note that you should check the value of counter to avoid a division by zero.
If you want the average to be in decimals, change the type of average to double: double average; and cast the division to double: average = (double) sum / counter;.

Why sum of odd numbers from 1 to the number entered doesn't match what was expected?

import java.util.Scanner;
public class OddSum {
public static void main(String[] args) {
int num;
int i = 1;
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
num = input.nextInt();
input.close();
while (i<=num) {
i += 2;
sum +=i;
}
System.out.println("The sum of odd numbers between 1 and" + num + "is: " + sum);
}
}
I wrote this code to sum up the odd numbers from 1 to a number entered.
Now, when I entered 8, I got the output as 24, against the desired output 16.
Can you tell me what went wrong?
You are incrementing the variable before performing summation .
while (i<=num) {
sum +=i;
i += 2;
}
You should add i to sum before adding to 2 to i. Thus, once i goes past num, the while loop will no longer execute.
import java.util.Scanner;
public class OddSum {
public static void main(String[] args) {
int num;
int i = 1;
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
num = input.nextInt();
input.close();
while (i<=num) {
// add i to sum before adding 2 to i
sum += i;
i += 2;
}
System.out.println("The sum of odd numbers between 1 and" + num + "is: " + sum);
}
Lets debug the code together:
after taking the number it would go to i<=num that while condition. Great, Then instead of getting sum it would + again 2 which cause 3. So what's happen? First case, 1 is not added before and first iteration value 1 is lose. That means whenever, you enter the loop. It goes increases before adding the previous value. So, rewrite the code this way:
while (i<=num) {
sum +=i;
i += 2;
}
You may use for instead:
for(int i=1;i<=num;i+=2){
sum +=i;
}
You're incrementing i before you sum it, instead of afterwards:
while (i <= num) {
sum +=i;
i += 2;
}
It's worth noting, though, that these kind of issues, where the loop variable is incremented by a constant, are often more convenient to write with a for loop:
for (int i = 1; i <= num; i += 2) {
sum += i;
}
Or better yet, if you're using Java 8, by collecting a stream:
int sum = IntStream.rangeClosed(1, num).filter(i -> i % 2 != 0).sum();
The reason why the result for your example with N = 8 gives 24 is because when i reaches value 7, the loop is continued and is added the value 9 to your sum too and you forget to add the first odd number: 1, because you start over from adding directly 3 to your sum.
You can either switch the statements between each other, either use a for loop instead of while:
for(int i = 1; i <= num; i += 2) {
sum += i;
}

Trying to take average each time something is added

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

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