My 'if' statement is not working properly - java

I have an assignment where I am supposed to determine whether the average of three values is 'above average' or 'below average'. For some reason whatever is input will always be above average as the result. Here is my code below, thank you for any help!
import java.util.Scanner;
class Lesson_12_Activity_One {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter three values");
double x = scan.nextDouble();
double y = scan.nextDouble();
double z = scan.nextDouble();
double t = (double)Math.round(100*((x+y+z)/3));
System.out.print("The average is " + (t/100));
if(t >= 89.5)
System.out.print(" ABOVE AVERAGE");
else
System.out.print(" BELOW AVERAGE");
}
}

The average is t/100 but in your condition you test if t > 89.5 (which is always true since t is the average multiplied by 100).
Just remove both the multiplication by 100 and the division by 100. They don't seem necessary.
double t = Math.round((x+y+z)/3);
System.out.print("The average is " + t);
if(t >= 89.5)
System.out.print(" ABOVE AVERAGE");
else
System.out.print(" BELOW AVERAGE");
}

if(t/100 >= 89.5)
System.out.print(" ABOVE AVERAGE");
else
System.out.print(" BELOW AVERAGE");
by the way why are you multiplying and then dividing by 100?

I'm gonna guess that you're mixing up perunages and percentages. That means, at one point in your program you use 0.5 and in the other 50, both as 50%.
double t = (double)Math.round(100*((x+y+z)/3));
System.out.print("The average is " + (t/100));
With x, y and z all as 50, this will output 50. t = 100 * (50 + 50 + 50)/3 = 5000, the output is (t/100) = 50.
if(t >= 89.5) however tests with t = 5000.
To solve this, go down one of two paths.
Replace all percentages for perunages. This means inputting numbers from 0 to 1.
To do this, do the following:
change your t-initialization for double t = (double)Math.round(1000*((x+y+z)/3)) / 1000 This will make T be in between 0 and 1 with 3 digits precision.
Replace your if with if (t >= 0.895)
Replace all perunages with percentages. This means inputting numbers from 0 to 100.
To do this, remove the 100* from your double t = (double)Math.round(100*((x+y+z)/3));, and the /100 from the output message.

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

Print only 10 outputs per line

I have a Printf formating question. I am to print only 10 numbers, before going to the next line and printing 10 more numbers and so on. with the end goal being like a table, with all the columns lining up and being aligned to the right. I am using a while statement as well. I have tried a few different things that I have found in my research, with no success. Would I use a different print statement for it other than Printf? Such as Print, or PrintLn? Also thought about using an If statement as well. Any help would be greatly appreciated! Thank you.
System.out.printf("Please enter a maximun integer value: ");
Scanner scan = new Scanner(System.in);
double n = scan.nextDouble();
System.out.printf("The number you entered was: %.0f \n", n); // Just to check if user input is correct
double startNum = 0;
double sqrt = startNum;
System.out.printf("Squares less than %.0f are: ", n);
while ( sqrt < n) {
sqrt = Math.pow(startNum, 2);
System.out.printf("%6.0f", sqrt);
startNum ++;
}
Using a MOD condition, You can ensure 10 output per line.
import java.util.Scanner;
class Test {
public static void main(String[] args) {
System.out.printf("Please enter a maximun integer value: ");
Scanner scan = new Scanner(System.in);
double n = scan.nextDouble();
System.out.printf("The number you entered was: %.0f \n", n); // Just to check if user input is correct
double startNum = 0;
double sqrt = startNum;
System.out.printf("Squares less than %.0f are: ", n);
while (sqrt < n) {
sqrt = Math.pow(startNum, 2);
if(startNum != 0 && startNum % 10 == 0) {
System.out.println();
}
System.out.printf("%6.0f", sqrt);
startNum++;
}
}
}
Output -
Please enter a maximun integer value: 150
The number you entered was: 150
Squares less than 150 are: 0 1 4 9 16 25 36 49 64 81
121 144 169
while ( sqrt < n) {
sqrt = Math.pow(startNum, 2);
System.out.printf("%6.0f", sqrt);
startNum ++;
if(startNum%10==0){
System.out.printf("/n");
}
}

Trying to Understand Where My Loop Goes Wrong

So here is my task:
A postal company for a package charges $15 for the first
pound or a fraction thereof and $10 per pound for anything over one
pound. Write a program that prints the charge of a package.
Variables:
weight
First execution:
Weight? -12 Weight must be a positive number.
Second Execution:
Weight? 0 Weight must be a positive number.
Third Execution:
Weight? 2 Pay: $25.00
Forth Execution:
Weight? 2.8 Pay: $33.00
Fifth Execution:
Weight? 2.07 Pay: $25.70
and Here is the code I have developed so far:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else if (weight == 1) {
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
} else {
for (double i = 1; i < weight; i = i + .01) {
if (weight > 1) {
output = output + (1 / 10.00);
}
}
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
}
}
Everything works, but what I can't figure out is why (especially in the Fourth and Fifth Execution) is the final output always .10 cents off. Can anyone help me get to the accuracy I need?
Here is what I came up with:
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else {
// Print the charge of the package
if (weight > 1) {
output = cost + ((weight-1) * 10);
} else {
output = cost;
}
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
This should handle all of your cases, as well as numbers between 0 and 1 assuming it's $1 per 0.1 lbs. Instead of your for-loop, you can just use the cost + ((weight-1) * 10) formula. I removed the check to see if weight was equal to 1 because it's handled in the else clause.
If I understand the question correctly, you should never have any fractional dollar amount because anything over a pound is automatically rounded up to the next pound. ie: 2.01 lbs would become 3 lbs. If this is correct, then you could use Math's ceil function to round the weight up to the nearest whole pound, then do something like this:
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else if (weight == 1) {
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
} else {
double temp = (Math.ceil(weight)) - 1;
for(double i = temp; i > 0; i-- ) {
output += 10;
}
output += cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
}
}
This way, you don't need to bother with 10 cent increments. I hope this helps. Let me know if you have any questions.
This: double i = 1; i < weight; i = i + .01 could be your problem.
Doubles are not exact for decimal math. You're expecting i == weight, at which point the loop should stop, but it might not because i + .01 (however many times) is a tiny fraction less than weight.
My advice is to ditch the loop. If the package is over 1 lb, just subtract one pound from the weight, multiply by the $10 per pound, and then round to the two decimal places you need (NOTE: round it according to how it's spec'd to be rounded, don't just let the conversion from double to decimal do it on its own. There are multiple ways to round something, and decimal does not magically know which one is right for your problem.)
EDIT: Look at your solution, is it supposed to only work to a resolution of 1/10 of a lb? If so, start by rounding the weight. Again, round it according to how it needs to be rounded (down, up, or nearest).

Java: How to infinitely enter numbers, stop when negative number is entered and computer the average

I am trying to write a Java program that takes in a potentially infinite number of values - and once the user enters a negative number, the program stops, computes the average of all of the entered numbers (excluding the negative one) and prints out how many numbers were entered (once again, not the negative one) as well as the average.
Below is the code I currently have. When I try to run the program, it does not computer the average correctly and you have to enter a couple consecutive negative numbers for it to finally stop the program.
To test the arithmetic and the rest of the program, I inserted a statement that would close the program if the word "negative" was entered rather than a negative number. When did this, the average and count and everything else worked just like it was made to. Essentially, the problems start to occur when I try to stop the program after a negative number.
I am a beginning programmer and this has been driving me crazy for a couple hours. Any help is greatly appreciated!
import java.util.*;
import java.lang.Math;
import java.io.IOException;
import java.io.InputStream;
public class Average
{
public static void main(String[] args)
{
Scanner numInput = new Scanner(System.in);
double avg = 0.0;
double count = 0.0;
double sum = 0.0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
while (numInput.hasNextDouble())
{
double negNum = numInput.nextDouble();
if (negNum >= 0)
{
sum += numInput.nextDouble();
count++;
avg = sum/count;
}
else
{
System.out.println("You entered " + count + " numbers averaging " + avg + ".");
break;
}
}
}
}
You should use: sum+=negNum; instead of sum += numInput.nextDouble();
As it is now, your program, reads a number and if it is not negative it reads another number and adds it to the sum.
Also, you should compute the average only once in the else block.
You are reading a new number to compute the sum.
It should be
sum += negNum;
You have already received the number entered by the user in line:
double negNum = numInput.nextDouble();
You should add this number itself to sum rather than asking for another number from user by calling numInput.nextDouble() again. So the fixed code would be:
public static void main(String[] args){
Scanner numInput = new Scanner(System.in);
double avg = 0.0;
double count = 0.0;
double sum = 0.0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
while (numInput.hasNextDouble())
{
double negNum = numInput.nextDouble();
if (negNum >= 0)
{
sum += negNum;
count++;
avg = sum/count;
}
else
{
System.out.println("You entered " + count + " numbers averaging " + avg + ".");
break;
}
}
}
Sample Run:
Enter a series of numbers. Enter a negative number to quit.
2
3
-1
You entered 2.0 numbers averaging 2.5.
Change
sum += numInput.nextDouble(); // reading next value again
to
sum += negNum;

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

Categories

Resources