Mooc.fi Exercise: Average of positive numbers fail - java

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

Related

A Java program with a loop that allows the user to enter a series of integers, then displays the smallest and largest numbers + the average

I've got an assignment that requires me to use a loop in a program that asks the user to enter a series of integers, then displays the smallest and largest numbers AND gives an average. I'm able to write the code that allows the user to enter however many integers they like, then displays the smallest and largest number entered. What stumps me is calculating the average based on their input. Can anyone help? I'm sorry if my code is a little janky. This is my first CS course and I'm by no means an expert.
import javax.swing.JOptionPane;
import java.io.*;
public class LargestSmallest
{
public static void main(String[] args)
{
int number, largestNumber, smallestNumber, amountOfNumbers;
double sum, average;
String inputString;
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
largestNumber = number;
smallestNumber = number;
sum = 0;
for (amountOfNumbers = 1; number != -99; amountOfNumbers++)
{
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
if (number == -99)
break;
if (number > largestNumber)
largestNumber = number;
if (number < smallestNumber)
smallestNumber = number;
sum += number;
}
average = sum / amountOfNumbers;
JOptionPane.showMessageDialog(null, "The smallest number is: " + smallestNumber + ".");
JOptionPane.showMessageDialog(null, "The largest number is: " + largestNumber + ".");
JOptionPane.showMessageDialog(null, "The average off all numbers is: " + average + ".");
}
}
The problem is that you do an extra
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
at the beginning. You don't count that in a sum. That's why you get unexpected results.
The fix would be:
replace the declarations line with:
int number = 0, largestNumber, smallestNumber, amountOfNumbers;
Remove
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
That go before the loop
Replace for (amountOfNumbers = 0 with for (amountOfNumbers = 1
This is my first CS course
Then allow me to show you a different way to do your assignment.
Don't use JOptionPane to get input from the user. Use a Scanner instead.
Rather than use a for loop, use a do-while loop.
Usually you declare variables when you need to use them so no need to declare all the variables at the start of the method. However, be aware of variable scope.
(Notes after the code.)
import java.util.Scanner;
public class LargestSmallest {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int largestNumber = Integer.MIN_VALUE;
int smallestNumber = Integer.MAX_VALUE;
int number;
double sum = 0;
int amountOfNumbers = 0;
do {
System.out.print("Enter an integer, or enter -99 to stop: ");
number = stdin.nextInt();
if (number == -99) {
break;
}
if (number > largestNumber) {
largestNumber = number;
}
if (number < smallestNumber) {
smallestNumber = number;
}
sum += number;
amountOfNumbers++;
} while (number != -99);
if (amountOfNumbers > 0) {
double average = sum / amountOfNumbers;
System.out.printf("The smallest number is: %d.%n", smallestNumber);
System.out.printf("The largest number is: %d.%n", largestNumber);
System.out.printf("The average of all numbers is: %.4f.%n", average);
}
}
}
largestNumber is initialized to the smallest possible number so that it will be assigned the first entered number which must be larger than largestNumber.
Similarly, smallestNumber is initialized to the largest possible number.
If the first value entered is -99 then amountOfNumbers is zero and dividing by zero throws ArithmeticException (but maybe you haven't learned about exceptions yet). Hence, after the do-while loop, there is a check to see whether at least one number (that isn't -99) was entered.
You don't need to use printf to display the results. I'm just showing you that option.

how do I display the correct output when no positve numbers are entered

I'm new to coding. Assignment is to calculate the average of all the positive numbers input and exit when a zero is input. If no positive numbers are input display a message average not possible.
The following is what I have so far. I am stuck on the part about printing out the message "cannot calculate the average" when only a zero or negative numbers are input.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
int sumOfNumbers = 0;
double averagePositive = 0;
while (true) {
System.out.println("Give a number: ");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0)
break;
if (number > 0)
sumOfNumbers = number + sumOfNumbers;
if (number > 0)
numbers = numbers + 1;
if (number > 0)
averagePositive = (double)sumOfNumbers / (double)numbers;
}
System.out.println(averagePositive);
}
Try it as follows...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Give a number: ");
int num=input.nextInt();
int tot=0; //total
int count=0; // counting the positive numbers
if(num>0){
while(num!=0){
tot+=num;
count++;
System.out.print("Give a number: ");
num=input.nextInt();
if(num<0){
System.out.print("Not possible");
return;
}
}
double avg =(double)tot/n;
System.out.print("Average: "+avg);
}else{
System.out.println("Cannot calculate the average.");
}
}
I'd probably do it like this to keep it simple. Also in general, try not to cramp code together. Most formal project demand a certain degree of styling and usually spaces between operators and braces, etc... is required. In the long run it makes the code more readable and easier to maintain.
In your code there was no need to repeat the same if test for number > 0 multiple times, they could have all been bundled together. If the program was bigger and more complex I may have named the variable names with more qualification but for a short program like this, brief names were sufficient for clarity.
continue and break are important keywords to control loop behavior and can be used to increase brevity and clarity. continue goes back to the top of the loop immediately and break exits the innermost loop immediately. Dividing a double by an int yields a double so I was able to eliminate a cast. And the += operator makes it a little easier to read the line.
Also in Java and C any if() or else clause that contains one line doesn't require braces and unless a program is nested in such a way that adding the braces anyway adds to the clarity, it is often clearer to omit the braces in that case. The if statement illustrates both ways in a single statement.
import java.util.Scanner;
public class avg
{
static int count = 0;
static double sum = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("\nEnter a sequence of positive numbers (0 to calculate average):\n");
while (true) {
System.out.print("Number? ");
int n = scanner.nextInt();
if (n < 0) {
System.out.println("Negative numbers not allowed.");
continue;
} else if (n == 0)
break;
sum += (double)n;
++count;
}
System.out.println("Average of " + count + " numbers = " +
(double)(sum / count) + "\n");
System.exit(1);
}
}
Sample output:
$ java avg
Enter a sequence of positive numbers (0 to calculate average)
Number? 1
Number? 2
Number? 3
Number? 4
Number? 5
Number? -6
Negative numbers not allowed.
Number? 0
Average of 5 numbers = 3.0

Averaging grades math not displaying correctly

Can not for the life of me figure out why my average is not displaying correctly I've looked at it for like 2 hours.
import java.util.Scanner;
public class midterm
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int examScore =0;
int averageExamScore = 0;
int numStudent=0;
int sum=0;
while(examScore >= 0)
{
System.out.println("Enter exam scores (enter negative number to quit): ");
examScore = keyboard.nextInt();
numStudent++;
sum = sum + examScore;
}
if(numStudent > 0)
{
averageExamScore = sum/numStudent;
}
else
{
System.out.println("No scores to average");
}
}
}
The issue here is integer division.
averageExamScore = sum/numStudent;
All three of these arguments are integers, which means:
If you cast a part of your quotient to double, you'd lose precision (and fail compilation)
Example:
averageExamScore = (double)sum/numStudent; // wouldn't compile
The floor of the quotient sum/numStudent is provided instead of the whole number (so for a number like 4.9 you'd get 4).
You can fix this in a few ways:
Declare averageExamScore to be a double. This is required.
Either cast sum or numStudent to a double, or change their type to double.
You have defined averageExamScore as an integer, so integer arithmetic will be applied.
e.g.
5 / 2 == 2
1 / 2 == 0
Make averageExamScore into a double, and also cast your other integers to doubles.
Edit
To print out
do
if(numStudent > 0)
{
averageExamScore = sum/numStudent;
System.out.println ("average score is " + averageExamScore );
}
Go through the following code,
public class MidTerm {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int examScore = 0;
double averageExamScore = 0;
int numStudent = 0;
int sum = 0;
while (true) {
System.out.print("Enter exam scores (enter negative number to quit): ");
examScore = keyboard.nextInt();
if (examScore >= 0) {
numStudent++;
sum += examScore;
} else break;
}
if (numStudent > 0) {
averageExamScore = sum / numStudent;
System.out.println("Avarage score is : " + averageExamScore);
} else System.out.println("No scores to average");
}
}
averageExamScore variable should be a double otherwise it can not stored floating point values
Good Luck !!!

Java sum of numbers error

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

Doing one more iteration after DO-While loops stops?

I am writing a Babylonian algorithm for computing the square root of a positive number, and the iteration should keep going until the guess is within 1% of the previous guess.
the code that I have written gets the iteration going to the one before error is 1%. how can I make it to do one more iteration ?
to get the question straight, is there a way to tell it iterate untill the error is <1% ?
import java.util.Scanner;
public class sqrt {
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.print("\nplease enter the desired positive number in order to find its root of two: ");
double num = kb.nextDouble();
double guess=0;
double r, g1, error;
if (num>=0){
guess = num/2;
do{
r = num/guess;
g1 = guess;
guess = (guess+r)/2;
error = (guess-g1)/guess;
if (error<0){
error = -error;
}
}
while(error>0.01);
System.out.println("The square root of the number " + num +" is equal to " +guess);
} else {
System.out.println("Sorry the number that you entered is not a positive number, and it does not have a root of two");
}
}
}
Add a new counter that only gets increased in the (former) exit loop condition.
int exit = 0;
do {
...
if (error <= 0.01) {
exit++;
}
} while (exit < 2);
If you want to return a value only when the error is strictly less than 1%, you need to change the while condition.
Changing it to error >= 0.01 says "iterate, even when error is exactly equal to 1%, so we get a final error less than 1%".
Also, your if (num <= 0) allows a division by zero to happen, when num is exactly zero.
Let's check:
num = 0;
guess = num / 2; // guess = 0
r = num / guess; // r = 0 / 0
Looking at the below code should give you a clearer idea. I've commented it.
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("\nPlease enter the desired positive number in order to find its root of two: ");
double num = kb.nextDouble();
double guess=0;
double r, g1, error;
// Previous code allowed a division by zero to happen.
// You may return immediately when it's zero.
// Besides, you ask clearly for a *positive* number.
// You should check firstly if the input is invalid.
if (num < 0) {
System.out.println("Sorry the number that you entered is not a positive number, and it does not have a root of two");
}
// Since you assigned guess to zero, which is the sqrt of zero,
// you only have to guess when it's strictly positive.
if (num > 0) {
guess = num/2;
// Notice the slight change in the while condition.
do {
r = num/guess;
g1 = guess;
guess = (guess+r)/2;
error = (guess-g1)/guess;
if (error < 0) {
error = -error;
}
} while(error >= 0.01);
}
// Finally, print the result.
System.out.println(
"The square root of the number " + num +
" is equal to " + guess
);
}

Categories

Resources