Separating my Java code into two methods - java

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

Related

Getting error while creating bmi calculator

Im creating a bmi caculator and im using the height and weight formula. I keep getting an erorr that says nan obese at the very end and i dont know what i'm missing or what i need to edit. Any help would be appreciated.
Output error:
Enter Weight in pounds: 150
Enter height (ft.):
6
Enter height (in.):
7
Your BMI is: NaN
Obese
BMI formula:
BMI = (703 * weightInPounds) / heightInInches^2
Code:
import java.util.Scanner;
public class Bmi_Calc {
public static void main(String[] args) {
// TODO Auto-generated method st
Scanner input = new Scanner(System.in);
//double weight;
double weightInPounds;
int feet;
int inches;
//int weightInPounds;
int heightInInches;
double height;
System.out.print("Enter Weight in pounds: ");
double weight = input.nextDouble();
System.out.println("Enter height (ft.): ");
feet = input.nextInt();
System.out.println("Enter height (in.): ");
inches = input.nextInt();
weightInPounds = 0;
heightInInches = 0;
double bmi = (703 * weightInPounds) / Math.pow(heightInInches, 2.0);
double heightMeters = ((feet * 12) + inches) * .0254;
System.out.println("Your BMI is: " + bmi);
if (bmi < 18.5) {
System.out.println("Underweight.");
}
if ((bmi >= 18.5) && (bmi < 24.9)) {
System.out.println("Normal weight");
}
if ((bmi >= 25) && (bmi < 29.9)) {
System.out.println("Overwight");
}
else {
System.out.println("Obese");
}
input.close();
}
}
Check your bmi calculation numbers. That will tell you why you are getting NAN.
weightInPounds = 0;
heightInInches = 0;
double bmi = (703 * weightInPounds) / Math.pow(heightInInches, 2.0);
In above weightInPounds and heightInInches are zero so bmi = 0/0 which is causing NaN
Thanks

Class Average Methods, and array

This is the prompt that I'm asked to follow.
Write a method called average that takes in an array of test grades and returns the letter grade
of the class average.
The grade ranges are as follows:
average >= 90 -> A
80 <= average < 90 -> B
70 <= average < 80 -> C
60 <= average < 70 -> D
average < 60 -> F
Use the following method header: public static char average(int[] grades)
This is the output example I'm supposed to follow.
How many grades do you want to enter? 10
Enter grade 1: 70
Enter grade 2: 87
Enter grade 3: 95
Enter grade 4: 80
Enter grade 5: 80
Enter grade 6: 78
Enter grade 7: 85
Enter grade 8: 90
Enter grade 9: 66
Enter grade 10: 89
The class average for the test is: B
This is what I have so far but I don't know how to include the method header stated above. public static char average(int[] grades)
import java.util.Scanner;
public class ClassAverage{
//Main Method
public static void main(String[] args){
//Variables
char average;
int i;
int sum = 0;
int b;
Scanner scan = new Scanner(System.in);
System.out.print("How many grades do you want to enter: ");
int grades = scan.nextInt();
int array[] = new int[grades];
for(i = 0;i < grades; i++){
System.out.print("Enter grade " + (i + 1) + ": ");
array[i] = scan.nextInt();
sum = sum + array[i];
}
b = sum / array.length;
if(b >= 90)
average = 'A';
else if(b <= 90 && b >= 80)
average = 'B';
else if(b <= 80 && b >= 70)
average = 'C';
else if(b <= 70 && b >= 60)
average = 'D';
else if(b <= 60)
average = 'F';
else
average = '?';
System.out.println("The class average for the test is: " + average);
}
}
public class MainClass {
//Main Method
public static void main(String[] args) {
//Variables
char avg;
int i;
Scanner scan = new Scanner(System.in);
System.out.print("How many grades do you want to enter: ");
int grades = scan.nextInt();
int array[] = new int[grades];
for (i = 0; i < grades; i++) {
System.out.print("Enter grade " + (i + 1) + ": ");
array[i] = scan.nextInt();
}
avg = average(array);
System.out.println("The class average for the test is: " + avg);
}
private static char average(int[] array) {
final int sum = Arrays.stream(array).sum();
final int b = sum / array.length;
if (b >= 90) {
return 'A';
} else if (b <= 90 && b >= 80) {
return 'B';
} else if (b <= 80 && b >= 70) {
return 'C';
} else if (b <= 70 && b >= 60) {
return 'D';
} else if (b <= 60) {
return 'F';
} else {
return '?';
}
} }
See that i accepted all the marks into an array and passed that int array into a method where i calculated the sum and grade and returned grade
Your instructor wants you to create a method called average that could be called from within main.
Essentially, all you need to do to complete the assignment is wrap your code inside of that method. So main would call average having passed in the ints to it.
I've written some pseudocode to help you take the code you have now and encapsulate it in the method you are requesting.
You already have the pieces written, you just need to move them from your main method to this new average method and make any necessary changes that come with changing scope (declaring or renaming certain variables in the new method).
Then to get the desired output you can call the method from within main by using average(gradeArray) and using the char value returned in a print statement.
public static char average(int[] gradeArray) {
// Find the sum of grades in gradeArray
// Use this sum and the size of the array to compute the average
// Use logic to determine which letter grade to print out based on the average
// Return the average
}
It is very simple code. My answer is
import java.util.Scanner;
public class AverageMethod {
public static void main(String[] args) {
char average;
int i;
int sum = 0;
int b;
Scanner scan = new Scanner(System.in);
System.out.print("How many grades do you want to enter: ");
int grades = scan.nextInt();
int array[] = new int[grades];
for(i = 0;i < grades; i++){
System.out.print("Enter grade " + (i + 1) + ": ");
array[i] = scan.nextInt();
sum = sum + array[i];
}
b = sum / array.length;
if(b<=100 && b>=0){
if(b<=100 && b >= 90)
average = 'A';
else if(b >= 80)
average = 'B';
else if(b >= 70)
average = 'C';
else if(b >= 60)
average = 'D';
else
average = 'F';
System.out.println("The class average for the test is: " + average);
}else{
System.out.println("Not in range");
}
}
}
I am also add my github uploaded coed for you. If you have any trouble please follow my githublink. Please study it for more clarification.
Another solution:
package test163;
import java.util.Scanner;
public class ClassAverage {
//Main Method
public static void main(String[] args) {
//Variables
char average;
int i;
int b;
Scanner scan = new Scanner(System.in);
System.out.print("How many grades do you want to enter: ");
int grades = scan.nextInt();
int array[] = new int[grades];
for (i = 0; i < grades; i++) {
System.out.print("Enter grade " + (i + 1) + ": ");
array[i] = scan.nextInt();
}
average = average(array);
System.out.println("The class average for the test is: " + average);
}
public static char average(int[] grades) {
int sum = 0;
for (int grade: grades) {
sum += grade;
}
int b = sum / grades.length;
if (b >= 90) {
return 'A';
} else if (b >= 80) {
return 'B';
} else if (b >= 70) {
return 'C';
} else if (b >= 60) {
return 'D';
} else {
return 'F';
}
}
}

BMI Calculator not printing results

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

Calculating change from 2 inputs by a user

i am trying to output the minimum amount of notes needed from two inputs. one being the cost and the other being the amount handed over by the customer.
so if i enter 400 and then 500, it should say 2 $50 dollars notes.
or if i enter 60 and then 80, it should say 1 $20 dollar note.
this is a small bit of my code:
import java.util.Scanner;
public class bank {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter amount due: ");
int amount = input.nextInt();
System.out.println("Amount tendered: ");
int tmp = input.nextInt();
int change;
if(amount >= 50)
{
change =(tmp - amount)/50;
System.out.println (change + " $50 bills");
}
if(amount >= 20)
{
change =(tmp - amount)/20;
System.out.println (change + " $20 bills");
}
You can achieve it by using mod operator %
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter amount due: ");
int amount = input.nextInt();
System.out.println("Amount tendered: ");
int tmp = input.nextInt();
int change;
int diff = tmp - amount;
if (diff % 50 == 0) {
change = diff / 50;
System.out.println(change + " $50 bills");
}
else if (diff % 20 == 0) {
change = diff / 20;
System.out.println(change + " $20 bills");
}
}
Once you calculate the amount of change in a value of a bill, you need to lower the amount of change required. This is done in the code changeRequired = changeRequired - change;
System.out.println("Amount tendered: ");
int tmp = input.nextInt();
int changeRequired = tmp - amount;
int change;
if(amount >= 50)
{
change =(changeRequired)/50;
changeRequired = changeRequired - change;
System.out.println (change + " $50 bills");
}
if(amount >= 20)
{
change =(changeRequired )/20;
changeRequired = changeRequired - change;
System.out.println (change + " $20 bills");
}
Once you get your change which is the variable amount, you can use the following code to find out how many notes of each of the $50, $20, $10, $5, $1 there are in the change. The number of notes is minimal.
numOf50 = 0; // number of $50 dollar bills, the rest is similar.
numOf20 = 0; // ...
numOf10 = 0; // ...
numOf5 = 0;
numOf1 = 0;
if (amount / 50 > 1){
numOf50 += (amount / 50);
amount %= 50; // update the amount with the remainder
}
else if (amount / 20 > 1){
numOf20 += (amount /20);
amount %= 20;
}
else if (amount / 10 > 1){
numOf10 += (amount / 10);
amount %= 10;
}
else if (amount / 5 > 1){
numOf5 += (amount / 5);
amount %= 5;
}
else if (amount <=5 && amount >0){
numOf1 = amount;
}
// output is trivial, omitted.
Haven't tested on a machine but it should work or give you an idea.

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

Categories