BMI Calculator not printing results - java

As part of my CS studies we are starting to learn java and I wanted to do a little side project to try to get better at Java than I am.
So far it isn't working as it should.
I have written this code:
import java.util.Scanner;
public class BodyWeightCalculator {
public static void main(String[] args) {
double weight;
double height;
Scanner input = new Scanner(System.in);
System.out.print("What's your height in meters?");
height = input.nextDouble();
System.out.print("What's your weight in kilograms?");
weight = input.nextDouble();
double bmi = ((weight / height) / height);
System.out.printf("Your BMI is " + bmi);
if (bmi < 18.5)
System.out.println("Your BMI is " + bmi + ", you are underweight.");
else if (bmi <= 18.5 & bmi > 24.9)
System.out.println("Your BMI is " + bmi + ", you are at a normal weight.");
else if (bmi < 25 & bmi > 29.9)
System.out.println("Your BMI is " + bmi + ", you are overweight");
else if (bmi > 30) {
System.out.println("Your BMI is " + bmi + ", you are extremely overweight");
}
}
}
This programs asks the user to input his/her weight and height, and then it outputs the BMI of the user and whether he/she is of normal weight, or underweight, etc.
The program only outputs the BMI ignoring all the if-else statements.
Anything wrong with this?

You have an issue in the set of if-else statements, it should cover the whole ranges. And you should use the boolean operator '&&' rather than using the bitwise-operator '&'.
if (bmi < 18.5)
System.out.println("Your BMI is " + bmi + ", you are underweight.");
else if (bmi >= 18.5 && bmi <= 24.9)
System.out.println("Your BMI is " + bmi + ", you are at a normal weight.");
else if (bmi >= 25 && bmi <= 29.9)
System.out.println("Your BMI is " + bmi + ", you are overweight");
else if (bmi >= 30.) {
System.out.println("Your BMI is " + bmi + ", you are extremely overweight");
}

Your if-statements do not seem to cover the ranges that you are intending. Further, you should be using "&&" for "and" rather than "&", which is a bit-wise "and". You should also get in the habit of always using braces for if statement blocks, even if the block is one line.
You should rewrite your statements like so:
if (bmi < 18.5) {
System.out.println("Your BMI is " + bmi + ", you are underweight.");
}
else if (18.5 <= bmi && bmi < 25.0) {
System.out.println("Your BMI is " + bmi + ", you are at a normal weight.");
}
else if (25.0 <= bmi && bmi < 30.0) {
System.out.println("Your BMI is " + bmi + ", you are overweight");
}
else if (30.0 <= bmi) {
System.out.println("Your BMI is " + bmi + ", you are extremely overweight");
}
else {
throw new RuntimeException("Should not be reached. BMI=" + bmi);
}

Related

Separating my Java code into two methods

I want my main method to contain input values for a person’s weight and height and then for it to call for the bodyMassIndex method to get the health opinion (i.e. normal weight) which should then be output. Wondering if anyone could help me?
package bodymassindex;
import java.util.Scanner;
public class BodyMassIndex {
public static void main(String[] args) {
double m;
double kg;
double bmi;
Scanner input = new Scanner(System.in);
System.out.println("Enter weight (KG): ");
kg = input.nextDouble();
System.out.println("Enter height (M): ");
m = input.nextDouble();
bmi = kg / (m*m);
System.out.println("Your BMI is " + bmi);
if (bmi < 16)
System.out.println("Seriously underweight");
else if (bmi >= 16 && bmi < 18)
System.out.println("Underweight");
else if (bmi >= 18 && bmi < 24)
System.out.println("Normal weight");
else if (bmi >= 24 && bmi < 29)
System.out.println("Overweight");
else if (bmi >= 29 && bmi < 35)
System.out.println("Seriously overweight");
else if (bmi >= 35 )
System.out.println("Obese");
}
}
This breaks it down into its own method, and create a method which passes in some test parameters. Also includes functionality to take in user input still.
package bodymassindex;
import java.util.Scanner;
public class BodyMassIndex {
public static void main(String[] args) {
double m;
double kg;
Scanner input = new Scanner(System.in);
System.out.println("Enter weight (KG): ");
kg = input.nextDouble();
System.out.println("Enter height (M): ");
m = input.nextDouble();
bmi(kg, m);
// bmiTest(); /* Uncomment to run some "test" values.*/
}
private static void bmiTest() {
bmi(100, 2);
bmi(50, 1.3);
bmi(60, 1.8);
}
private static void bmi(double kg, double m) {
double bmi = kg / (m*m);
System.out.println("Your BMI is " + bmi);
if (bmi < 16)
System.out.println("Seriously underweight");
else if (bmi >= 16 && bmi < 18)
System.out.println("Underweight");
else if (bmi >= 18 && bmi < 24)
System.out.println("Normal weight");
else if (bmi >= 24 && bmi < 29)
System.out.println("Overweight");
else if (bmi >= 29 && bmi < 35)
System.out.println("Seriously overweight");
else if (bmi >= 35 )
System.out.println("Obese");
}
}

Trying to compute payroll in java

I have to figure out if gross pay is between "so and so" it's "this" tax percentage, etc. I thought I was doing alright, but it keeps outputting every single tax answer as one answer if I enter a high number for hours worked... like this "Deductions are 275.0165.0770.0000000000001".
Am I also doing this an extremely long way because I'm overthinking?
Thanks so much for any help!
import java.util.Scanner;
public class prob2
{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
double range = (168);
System.out.println("Enter the number of hours worked in a week:");
double hours = in.nextDouble();
System.out.println("Enter rate per hour:");
double rate = in.nextDouble();
double overtimeHours = hours - 40;
double overtimePay = (overtimeHours * rate) * 1.5;
double basePay = (hours - overtimeHours) * rate;
double grossPay = basePay + overtimePay;
double socialSecurity = .1 * grossPay;
double medical = .06 * grossPay;
if (overtimeHours < 0 )
{
System.out.println("Number of overtime hours are " + 0);
}
else
{
System.out.println("Number of overtime hours are " + overtimeHours);
}
if (overtimeHours < 0 )
{
System.out.println("Base pay is " + hours * rate);
}
else
{
System.out.println("Base pay is " + basePay);
}
if (overtimeHours < 0 )
{
System.out.println("Overtime pay is " + 0);
}
else
{
System.out.println("Overtime pay is " + overtimePay);
}
if (grossPay < 0 )
{
System.out.println("Gross pay is " + hours * rate);
}
else
{
System.out.println("Gross pay is " + grossPay);
}
if (grossPay > 0 && grossPay < 43)
{
System.out.println("Deductions are " + socialSecurity + medical);
}
else
if (43.01 < grossPay && grossPay < 218.00)
{
System.out.println("Deductions are " + socialSecurity + medical + (.10 * grossPay));
}
else
if (218.01 < grossPay && grossPay < 753.00)
{
System.out.println("Deductions are " + socialSecurity + medical + (.15 * grossPay));
}
else
if (grossPay > 0 && 753.01 < grossPay && grossPay < 1762.00)
{
System.out.println("Deductions are " + socialSecurity + medical + (.25 * grossPay));
}
else
if (1762.01 < grossPay && grossPay < 3627.00)
{
System.out.println("Deductions are " + socialSecurity + medical + (.28 * grossPay));
}
}
}
Please wrap your sum into parenthesis:
System.out.println("Deductions are " + (socialSecurity + medical));
In this case it will create sum at first then concatenate result to string, otherwise it will concat socialSecurity then medical one by one.
The same rule is right for similar cases in your code.

Beginner java programming if-else statements inefficient code

My code is correct but it looks too big.I was wondering if it could be more efficient and with even fewer variables.Do you have any hints?Thanks
sample output
Enter three scores: 87 42 94
The lowest score was: 42
The average without the lowest score is: 90.5
The grade is: A
<code>
import java.util.Scanner;
public class GradeAverager
{
public static void main(String[] args)
{
int score1,score2,score3;
double average,average_no_lowest;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter three scores: ");
score1 = keyboard.nextInt();
score2 = keyboard.nextInt();
score3 = keyboard.nextInt();
average = (score1 + score2 + score3) / 3.0;
System.out.println();
System.out.println("The average is: " + average);
if (score1 < score2 && score1 < score3)
System.out.println("The lowest score was:" + score1);
else if (score2 < score1 && score2 < score3)
System.out.println("The lowest score was:" + score2);
else if (score3 < score1 && score3 < score2)
System.out.println("The lowest score was:" + score3);
if (score1 < score2 && score1 < score3){
average_no_lowest = (score2 + score3)/2.0;
System.out.println("The average without the lowest score is: " + average_no_lowest);
if(average_no_lowest > 90)
System.out.print('A');
else if(average_no_lowest < 90 && average_no_lowest > 80 )
System.out.print('B');
else if(average_no_lowest > 70 && average_no_lowest < 80)
System.out.print('C');
else
System.out.print('D');
}
else if (score2 < score1 && score2 < score3){
average_no_lowest = (score1 + score3)/2.0;
System.out.println("The average without the lowest score is: " + average_no_lowest);
if(average_no_lowest > 90)
System.out.print('A');
else if(average_no_lowest < 90 && average_no_lowest > 80 )
System.out.print('B');
else if(average_no_lowest > 70 && average_no_lowest < 80)
System.out.print('C');
else
System.out.print('D');
}
else if (score3 < score1 && score3 < score2){
average_no_lowest =(score1 + score3)/2.0;
System.out.println("The average without the lowest score is: " + (score1 + score3)/2.0);
if(average_no_lowest > 90)
System.out.print('A');
else if(average_no_lowest < 90 && average_no_lowest > 80 )
System.out.print('B');
else if(average_no_lowest > 70 && average_no_lowest < 80)
System.out.print('C');
else
System.out.print('D');
}
}
}
</code>
Your section of code which reads
if(average_no_lowest > 90)
System.out.print('A');
else if(average_no_lowest < 90 && average_no_lowest > 80 )
System.out.print('B');
else if(average_no_lowest > 70 && average_no_lowest < 80)
System.out.print('C');
else
System.out.print('D');
}
is duplicated 3 times. Put it into a method.
Don't be worried about performance until it is a proven problem. Be worried about how easy it is to read and maintain the code.
Code has 2 audiences - the compiler and humans. Humans matter more than compilers.
Store the lowest score in a variable e.g. lowest_score.
and do the average by (total - lowest_score) / 2
It is the most efficient
You can use the following code,these have fewer lines of code and gives the same output as you want::
public static void main(String[] args) {
int score1, score2, score3, status;
double average, average_no_lowest;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter three scores: ");
score1 = keyboard.nextInt();
score2 = keyboard.nextInt();
score3 = keyboard.nextInt();
average = (score1 + score2 + score3) / 3;
System.out.println("Average Score was:: " + average);
if (score1 < score2 && score1 < score3) {
status = 1;
System.out.println("The lowest score was:: " + score1);
} else if (score2 < score1 && score2 < score3) {
status = 2;
System.out.println("The lowest score was:: " + score2);
} else {
status = 3;
System.out.println("The lowest score was:: " + score3);
}
if (status == 1) {
average_no_lowest = (score2 + score3) / 2;
System.out.println("The average without the lowest score is: "
+ average_no_lowest);
} else if (status == 2) {
average_no_lowest = (score1 + score3) / 2;
System.out.println("The average without the lowest score is: "
+ average_no_lowest);
} else {
average_no_lowest = (score1 + score2) / 2;
System.out.println("The average without the lowest score is: "
+ average_no_lowest);
}
}

Proper msg display

I don't get any errors but I want to display this msg "No discount. Your total is $_"
using this code:
if (!(sales < 10))
System.out.print("No discount. " +
"Your total is: $" + (int)total);
inside this code:
if (!(sales < 10))
System.out.print("No discount. " +
"Your total is: $" + (int)total);
else if (sales >= 10 || sales <= 19)
rate = 0.20;
else if (sales >= 20 || sales <=49)
rate = 0.30;
else if (sales >= 50 || sales <=99)
rate = 0.40;
else if (sales > 100)
rate = 0.50;
else
System.out.println("Your discount is $" + (int)discount +
". Your total is: $" + (int)total);
and it does show but i only want it to show when sales< 10
but if sales is NOT < 10 then i want it to show "Your discount is $___. Your total is $____."
any help will be very much appreciated. thanks for your time.
whole code:
import java.util.Scanner;
public class SoftwareSales
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int sales = 99;
int quantity;
double total;
double rate = 0;
double discount;
System.out.print ("Enter amount of packages purchased: ");
quantity = keyboard.nextInt();
total = quantity * sales;
discount = total * rate;
total = total - discount;
if (sales < 10) {
if (sales >= 10 || sales <= 19)
rate = 0.20;
else if (sales >= 20 || sales <=49)
rate = 0.30;
else if (sales >= 50 || sales <=99)
rate = 0.40;
else if (sales > 100)
rate = 0.50;
System.out.println("Your discount is $" + (int)discount +
". Your total is: $" + (int)total);
} else {
System.out.print("No discount. " +
"Your total is: $" + (int)total);
}
}
}
Try this:
if (sales > 10) {
if (sales >= 10 || sales <= 19)
rate = 0.20;
else if (sales >= 20 || sales <=49)
rate = 0.30;
else if (sales >= 50 || sales <=99)
rate = 0.40;
else if (sales > 100)
rate = 0.50;
System.out.println("Your discount is $" + (int)discount +
". Your total is: $" + (int)total);
} else {
System.out.print("No discount. " +
"Your total is: $" + (int)total);
}
So why are you testing for the exact opposite of what you want to do? Notice the exclamation mark (!) which inverts your sales test in your first if. Remove that and your code should work as intended.

Stuck on Java program that tallies grades and shows results

I'm taking a beginners course in Java and they asked us to:
Write a program to tally the number of A's, B's, C's, D's and F's based upon a list of scores entered by a user.
After all the scores are entered, the program must display a
horizontal bar graph of the number tallied for each grade like that shown in the Operation section.
The tally graph must display a single '*' for each unit tallied.
When a user enters a -1, the program must display the final graph and
exit.
The output of your program must display prompts and a tally graph
like that shown in the Operation section above.
You may assume that a user will enter numbers only.
Operation:
The program starts and prompts you to either enter a test score or end
the program by entering a -1. Like the following:
Number of A's: 0
Number of B's: 0
Number of C's: 0
Number of D's: 0
Number of F's: 0
Enter a score (%) or -1 to end: 90
As you enter each score, the application decides whether the score is
an A, B, C, D or F and adds one to the letter-grade tally. Like the
following:
Number of A's: 1
Number of B's: 0
Number of C's: 0
Number of D's: 0
Number of F's: 0
Enter a score (%) or -1 to end: 95
Each time you enter a score, the program updates the tally. Like the following:
Number of A's: 2
Number of B's: 0
Number of C's: 0
Number of D's: 0
Number of F's: 0
Enter a score (%) or -1 to end: -1
When you are done entering scores, the program displays a horizontal
bar graph of the tally for A's, B's, C's, D's and F's. Like the
following:
A's: **
B's:
C's:
D's:
F's:
Specifications:
Numerical Grade Letter Grade
greater than or equal to 90 A
less than 90 but greater than or equal to 80 B
less than 80 but greater than or equal to 70 C
less than 70 but greater than or equal to 60 D
less than 60 F
When the program ends, display the number of scores, average score, and best score.
Example:
Number of scores: 2
Average score: 92.5
Best score: 95.0
We have also been instructed to code in at least two methods : one that has a void and one that returns something.
So far I have only been able to tally up the scores entered, but I don't seem to be able to wrap my head around recording all the inputs and calculating the average and picking out the best score
This is what I have so far :
import java.util.*;
public class ScoreTally {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
int scoreCount = -1;
double score = 0;
while (score != -1) {
if (score >= 90)
aCount++;
else if ((score < 90) && (score >= 80))
bCount++;
else if ((score < 80) && (score >= 70))
cCount++;
else if ((score < 70) && (score >= 60))
dCount++;
else if ((score < 60) && (score > 0))
fCount++;
System.out.println("Number of A's: " + aCount);
System.out.println("Number of B's: " + bCount);
System.out.println("Number of C's: " + cCount);
System.out.println("Number of D's: " + dCount);
System.out.println("Number of F's: " + fCount);
System.out.print("Enter a score (%) or -1 to end: ");
score = input.nextDouble();
scoreCount++;
}
if (score == -1)
System.out.println("Number of scores: " + scoreCount);
}
}
Use a function to return the greatest number to get your best score.
And another function to print the final graph.
That should take care of the two function requirement.
Also, make the loop an exit-controlled one, as it has to run atleast once.
As a coding practice, you should not be using star imports(import java.util.*) instead use only what you need.
Also, good work on setting the scoreCount to -1 in the beginning.
import java.util.Scanner;
public class ScoreTally {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
int scoreCount = -1;
double score;
double totalScore = 0;
double bestScore = -1;
do {
System.out.println("Number of A's: " + aCount);
System.out.println("Number of B's: " + bCount);
System.out.println("Number of C's: " + cCount);
System.out.println("Number of D's: " + dCount);
System.out.println("Number of F's: " + fCount);
System.out.print("Enter a score (%) or -1 to end: ");
score = input.nextDouble();
if (score >= 90) {
aCount++;
} else if ((score < 90) && (score >= 80)) {
bCount++;
} else if ((score < 80) && (score >= 70)) {
cCount++;
} else if ((score < 70) && (score >= 60)) {
dCount++;
} else if ((score < 60) && (score > 0)) {
fCount++;
}
scoreCount++;
totalScore = totalScore + score;
bestScore = greaterNumber(bestScore, score);
} while (score != -1);
printGraph('A', aCount);
printGraph('B', bCount);
printGraph('C', cCount);
printGraph('D', dCount);
printGraph('F', fCount);
System.out.println("Number of scores: " + scoreCount);
System.out.println("Average scores: " + totalScore / scoreCount);
System.out.println("Best scores: " + bestScore);
}
public static void printGraph(char grade, int count) {
System.out.print("Number of " + grade + "'s: ");
for (int i = 0; i < count; i++) {
System.out.print("*");
}
System.out.println();
}
public static double greaterNumber(double firstNum, double secondNum) {
if (firstNum >= secondNum) {
return firstNum;
} else {
return secondNum;
}
}
}
To begin with you already have the code to tally the results.
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
int scoreCount = -1;
What you need is another field that will hold the total score i.e.
int totalScore = 0;
You need to prompt for the first score before you enter the while loop otherwise it won't run properly the first iteration. At the end (or the beginning) you need to update totalScore with whatever was the input for that round, and not update it if the input was -1.
The average score will just be the totalScore/scoreCount you should compute that after you finish the while loop.
For the best score you can have another field for int = maxScore
you can update it every iteration of the loop with
maxScore = Math.max(maxScore, score);
Math.max returns the maximum of the two numbers.
It's rather simple. Declare 2 variables, one for having avgScore, one for in beginning of your program.
double bestScore = 0.0;
double avgScore = 0.0;
double totalScore = 0.0;
while (score != -1) {
totalScore = totalScore + score;
if(score > bestScore)
bestScore = score;
if (score >= 90)
aCount++;
else if ((score < 90) && (score >= 80))
bCount++;
else if ((score < 80) && (score >= 70))
cCount++;
else if ((score < 70) && (score >= 60))
dCount++;
else if ((score < 60) && (score > 0))
fCount++;
System.out.println("Number of A's: " + aCount);
System.out.println("Number of B's: " + bCount);
System.out.println("Number of C's: " + cCount);
System.out.println("Number of D's: " + dCount);
System.out.println("Number of F's: " + fCount);
System.out.print("Enter a score (%) or -1 to end: ");
score = input.nextDouble();
scoreCount++;
}
if (score == -1){
System.out.println("Number of scores: " + scoreCount);
avgScore = totalScore/scoreCount;
System.out.println("Best Score: " + bestScore);
System.out.println("Avg Score: " + avgScore);
}
Also for displaying the chart you can use your final tallies.

Categories