My problem is how can I implement without the Scanner method and with Math.round and Math.pow?
Here is my code:
import java.util.Scanner;
public class BMI{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Input weight in kilogram: ");
double weight = sc.nextDouble();
System.out.print("\nInput height in meters: ");
double height = sc.nextDouble();
double BMI = weight / (height * height);
System.out.print("\nThe Body Mass Index (BMI) is " + BMI + " kg/m2");
}
}
My another idea was It is only for a certain value. In my case with a weight of 75.0 and size 178.0
public static void main(String args[]) {
double weight = 75.0;
double height = 178.0;
double BMI = weight / (height * height);
System.out.print("\nThe Body Mass Index (BMI) is " + BMI + " kg/m2");
}
It's up to developer to choose how to initialize parameters.
If don't want to use scanner the simple way is just add directly.
Initialize can also come from various data-sources: database, file (xml,text), web-service, etc.
For school purpose maybe you could try to build a BMI class and use constructor to pass whatever parameters may want.
Advantage to have a constructor with parameters is that you can build various BMI instances with different result(based on params), not just have only 1 result in for all the class-instances (due to the fact the input is the same).
eg:
public class BMI
{
double BMI;
public BMI(double weight,double height )
{
this.BMI = weight / (height * height);
}
public String toString()
{
return "\nThe Body Mass Index (BMI) is " + this.BMI + " kg/m2";
}
public static void main(String args[])
{
BMI test1 = new BMI(100,1.90);
BMI test2 = new BMI(68.77,1.60);
System.out.println(test1);
System.out.println(test2);
}
}
Output:
The Body Mass Index (BMI) is 27.70083102493075 kg/m2
The Body Mass Index (BMI) is 26.863281249999993 kg/m2
Related
I build a program using JAVA to receive input from user to calculate their BMI and pass those values to another method name calculateBMI(). The problem currently is that when I want to return back the BMI to the main method, it will display the output as 0.0. Here is the code:
import java.util.Scanner;
public class StudentBMI{
//METHOD
static float calculateBMI(float weight, float height){
float bmi;
System.out.println("Your weight in KG is: " + weight);
System.out.println("Your height in M² is: " + (height/100));
return bmi = weight / (height/100)*(height/100);
}
//MAIN
public static void main(String[] args) {
float bmi=0;
Scanner input = new Scanner(System.in);
System.out.println("Please insert your weight in KG: ");
float weight = input.nextFloat();
System.out.println("Please insert your height in CM: ");
float height = input.nextFloat();
calculateBMI(weight, height);
System.out.println("Your BMI is: " + bmi);
}
}
The reason why I declared and initialized the value BMI as 0 in main method because when I declared without initialized it, console return error to initialized that variable but to be honest I'm not very sure about that one. Can anyone help me to figure out this problem?
First return the bmi value in your method without assignment.
Assign the return value to the bmi variable in the main mathod:
//METHOD
static float calculateBMI(float weight, float height){
System.out.println("Your weight in KG is: " + weight);
System.out.println("Your height in M² is: " + (height/100));
return weight / (height/100)*(height/100);
}
//MAIN
public static void main(String[] args) {
float bmi=0;
Scanner input = new Scanner(System.in);
System.out.println("Please insert your weight in KG: ");
float weight = input.nextFloat();
System.out.println("Please insert your height in CM: ");
float height = input.nextFloat();
bmi = calculateBMI(weight, height);
System.out.println("Your BMI is: " + bmi);
}
Please remove the bmi in your method. Assigning in the method will not reflect in your main method since it is not class variable or static variable.
The main method's bmi variable should get assignment of the method result.
import java.util.Scanner;
public class StudentBMI{
//METHOD
static float calculateBMI(float weight, float height){
System.out.println("Your weight in KG is: " + weight);
System.out.println("Your height in M² is: " + (height/100));
return weight / (height/100)*(height/100);
}
//MAIN
public static void main(String[] args) {
float bmi=0;
Scanner input = new Scanner(System.in);
System.out.println("Please insert your weight in KG: ");
float weight = input.nextFloat();
System.out.println("Please insert your height in CM: ");
float height = input.nextFloat();
bmi = calculateBMI(weight, height);
System.out.println("Your BMI is: " + bmi);
}
}
//your code return wrong value.you can check mine and compare it to your code
import java.util.Scanner;
public class StudentBMI{
static float calculateBMI(float weight, float height){
float bmi;
float calc;
System.out.println("Your weight in KG is: " + weight);
System.out.println("Your height in M² is: " + (height/100));
calc=(height/100)*(height/100);
bmi=weight/calc;
return bmi;
}
public static void main(String[] args) {
float bmi=0;
Scanner input = new Scanner(System.in);
System.out.println("Please insert your weight in KG: ");
float weight = input.nextFloat();
System.out.println("Please insert your height in CM: ");
float height = input.nextFloat();
System.out.println("Your BMI is: " + calculateBMI(weight, height));
}
}
When I try to run this code, it won't let me use "bmi". I'm trying to make a simple Body Mass Index calculator, but I don't understand why it won't work. If you could rewrite the code properly, it'd help me learn better.
import java.util.Scanner;
public class Bmi {
int weight;
int height;
int bmi = weight /(height*height) * 703;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter weight: ");
int weight = input.nextInt();
System.out.print("Enter height: ");
int height = input.nextInt();
System.out.println(bmi);
}
}
You are trying to use non static members inside static context.
You don't really need any instance/static variables here. Just go with local variables.
import java.util.Scanner;
public class Bmi {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter weight: ");
int weight = input.nextInt();
System.out.print("Enter height: ");
int height = input.nextInt();
int bmi = weight /(height*height) * 703;
System.out.println(bmi);
}
}
Although it is not happen in real world, when your height is greater than weight you end up in zero as integer division is happening. Better you change them to doubles. Give a read Why is the result of 1/3 == 0?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter weight: ");
double weight = input.nextInt();
System.out.print("Enter height: ");
double height = input.nextInt();
double bmi = weight / (height * height) * 703;
System.out.println(bmi);
}
Finally
int bmi = weight /(height*height) * 703;
That statement won't keep a track on values of weight and height. You need to reevaluate each time when they change.
You should never combine the worker and user code in a same class.
Better to create a separate class for calculator say BmiCalculator and define a static method to calculate bmi say calculateBmi. Static because its just dependent on the input it needs and nothing else.
Then call and use this static method directly in your CallerClass
Please refer the below code:
import java.util.Scanner;
class BmiCalculator {
public static double calculateBmi(double weight, double height){
return weight /(height*height) * 703;
}
}
public class CallerClass{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter weight: ");
double weight = input.nextInt();
System.out.print("Enter height: ");
double height = input.nextInt();
System.out.println(BmiCalculator.calculateBmi(weight,height));
}
}
It's because you trying to access instance context from static context. Simpliest way to fix this is add static modificator to your
fields and remove bmi calculation from bmi field assignment because all static is initialized when class loaded. More concise
way to write this code is that:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter weight: ");
int weight = input.nextInt();
System.out.print("Enter height: ");
int height = input.nextInt();
Bmi bmi = new Bmi(weight, height); //create new bmi instance
System.out.println(bmi.value()); // get it's value
System.out.println(bmi); // calls toString() method (object text representation)
//that we already override in Bmi class
}
}
We decouple Bmi calculation from user input with way to create separate class, now Bmi class knows nothing about user input and it's good because in this way we increased cohesion and reduce coupling in Main and Bmi classes.
It helps to code reuse in different projects and ease mantain efforts. See https://en.wikipedia.org/wiki/GRASP_(object-oriented_design) for more information.
public class Bmi { //place to separate file with name Bmi.java
private int weight;
private int height;
public Bmi(int weight, int height) {
this.weight = weight;
this.height = height;
}
/**
returns a bmi value
*/
public int value() {
return weight / (height * height) * 703;
}
public String toString() {
return value();
}
}
import java.util.Scanner ;
public class CollinsHealthCalculator {
double ACTIVITY_FACTOR = 1.375;
public static void main (String[] args) {
newHealthCalcDescription ();
Scanner keyboard = new Scanner (System.in);
System.out.println ("What is your weight in pounds? ");
double weightlb = keyboard.nextDouble ();
System.out.println ("What is your height in inches? ");
double heightin = keyboard.nextDouble ();
System.out.println ("What is your age in years? ");
double ageYears = keyboard.nextDouble ();
double WEIGHT_KILOGRAMS = weightlb / 2.2;
double HEIGHT_METERS = heightin * .0254;
double weightkg = WEIGHT_KILOGRAMS;
double heightm = HEIGHT_METERS;
double computingBMI (BMI, weightkg, heightm);
maleBMR (heightm, weightkg, ageYears);
femaleBMR (heightm, weightkg, ageYears);
showResults (BMI, caloriesm, caloriesf);
public static newHealthCalcDescription () {
System.out.println("This calculator will determine your BMI "
+ "(Body Mass Index). While also it will determine the amount "
+ "of calories needed to maintain weight.");
}
//Computing the BMI
public static void computingBMI (double BMI, double weightkg, double heightm){
BMI = weightkg/(Math.pow(heightm, 2));
}
//Computing BMR for male and female
public static void maleBMR (double heightm, double weightkg, double ageYears) {
double HEIGHT_CENTIMETERS = heightm * 100;
double heightcm = HEIGHT_CENTIMETERS ;
double BMRForMales = 13.397 * weightkg + 4.799 * heightcm - 5.677 * ageYears + 88.362;
double caloriesm = Math.round(BMRForMales * 1.375);
}
public static void femaleBMR (double heightm, double weightkg, double ageYears) {
double HEIGHT_CENTIMETERS = heightm * 100;
double heightcm = HEIGHT_CENTIMETERS ;
double BMRForFemales = 9.247 * weightkg + 3.098 * heightcm - 4.330 * ageYears + 447.593;
double caloriesf = Math.round(BMRForFemales * 1.375);
}
public static void showResults (double BMI, double caloriesm, double caloriesf) {
//Show results
System.out.printf ("%nYour BMI is: %7.1f", BMI);
System.out.println ("A BMI between 18.5 to 24.9 is considered normal.");
System.out.println ();
System.out.println ("To maintain current weight:");
System.out.print ("Men need to eat " + caloriesm);
System.out.println (" calories per day.");
System.out.print ("Females need to eat " + caloriesf);
System.out.println (" calories per day.");
}
}
I'm trying to get the code to pass down statements but I'm new to programming and have no clue on how to go about getting method passed down to another method. I've tried researching everywhere but I've had little luck in finding any help. Please help so I can make my programm functional I'm excited to learn just need help.
You can try giving the variables the global scope(outside the method). You may learn about it here.
When you declare a variable inside a method (i.e. code block), it is local to that block. So you cannot use that variable in any other method. Here the best option for you to do is to declare the variable, i.e. like weightkg etc as class variables.
You can change the return type of the methods from void to double and store the returned result and send the results to other methods.
for eg.
public static double computingBMI (double BMI, double weightkg, double heightm){
return weightkg/(Math.pow(heightm, 2));
}
I am new to java and I am trying to make this bmi calculator but I am having trouble returning and calling variables. I am sure that I am doing something very wrong but have been unable to figure out how to properly do this after searching the internet my guess is I do not know what I should be searching. I will post the code, I am getting 4 errors in my main that are as follows:
required: double,double,double,double
found: no arguments
reason: actual and formal argument lists differ in length
I am assuming that I have improperly set up my variables but could really use a bit of guidance. Thank you in advance.
import java.util.Scanner;
public class cs210 {
public double weight;
public double height;
public double bmi;
public double wcal;
public double mcal;
public double age;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
method1 ();
method2 ();
method3 ();
method4 ();
method5 ();
}
public static void method1 () {
System.out.println ("This program implements a Health Assistance Calculator ");
System.out.println ("Given a weight, height, and age, it will compute:\n");
System.out.println ("BMI - Body Mass Index");
System.out.println ("Calories needed per day to maintain weight");
}
public double method2 (double weight, double height, double wcal, double bmi) {
Scanner keyboard = new Scanner (System.in);
System.out.println ("Please enter your weight:");
weight = keyboard.nextDouble ();
System.out.println ("Press 1 if weight was entered in Kg \n Press 2 if weight was entered in Lbs");
double wunits = keyboard.nextDouble();
if (wunits == 1) {
System.out.println("Thank you");
} else if (wunits == 2){
weight = weight / 2.2;
System.out.println("Thank you");
}
else {
System.out.println ("Please try again");
return 0;
}
System.out.println("Please enter your height:");
height = keyboard.nextDouble ();
System.out.println ("Press 1 if height was entered in meters \n Press 2 if height was entered in inches");
int hunits = keyboard.nextInt();
if(hunits ==1) {
System.out.println("Thank you");
} else if (hunits == 2){
height = height / 0.0254;
}else {
System.out.println("Please try again");
return 0;
}
System.out.println("Please enter your age in years:");
age = keyboard.nextDouble ();
bmi = weight / Math.pow(height, height);
return ( bmi + age + height + weight);
}
public static double method3(double weight, double age, double height) {
double paf = 1.375;
double mcal;
mcal = (13.397 * weight + 4.799 * height + 5.677 * age + 88.362) * paf;
return mcal;
}
public static double method4(double weight, double age, double height, double paf){
double wcal;
wcal = (93247 * weight + 3.098 * height - 4.330 * age + 447.593) * paf;
return wcal;
}
public double method5(double bmi, double mcal, double wcal){
System.out.println("Your BMI is:" + bmi);
System.out.println("A BMI in the range of 18.5 to 24.9 is considered normal\n");
System.out.println("To maintain your current weight:");
System.out.println("Men need" + mcal + "per day");
System.out.println("Women need" + wcal + "per day");
return 0;
}
}
You define method2 like this:
public double method2 (double weight, double height, double wcal, double bmi) {
// ...
It has four parameters, all double, just like your error message said. Then you call it like this:
method2 ();
Without any parameters at all, again just like the error message said. Since you defined it with four parameters, every time you call it you need to do it with four parameters. The values you use as parameters will be the values that the variables weight, height, wcal and bmi gets inside the function, and if you don't have any parameters the computer will not know what values to use for those variables and therefore throw an error to complain. So you could, as an example, do it like this:
method2(34.9, 23.4, 23.5, 34.1); // Just picked four random numbers here.
But looking at the structure of your program, it looks like you don
t want to pass any values to the function at all (since you let the user enter the values inside the function). Then you could just get rid of the parameters, and declare the variables inside the function:
public double method2 () {
double weight, height, wcal, bmi;
// ...
Now the variables will be available inside method2, but not anywhere else. If you want to use the same values later in the other functions, you could instead of declaring them inside your function declare them in your class, and they will become available anywhere in your class, but not anywhere else.
You will have to fix the same issue with the parameters for method3, method4 and method5 as well.
You need to pass parameters when you call to methods. If you call to method
public double method2 (double weight, double height, double wcal, double bmi)
You need to call it to like this method2 (50, 2, 200, 25.5);
When you call in to your other methods such as method3, method4, method5 ; you have to give appropriate parameters to those. But when it comes to your method1. It will not expecting any parameters so you don't want to pass any parameter to that method.
I think this small document will help you to understand method and arguments.
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html
Its better to add your BMI logic and method to separate class then within the main method create and object and to the rest of manipulation. Otherwise it will hard to maintain and update properties and when you do it in that way remove your static methods. and use proper names for each and every method.
This code will give compilation errors because you have called methods in wrong way and you have call method2 and method5 within static method.
in method2() you have given 4 parameter but you are not using even a single parameter because you are getting from user.
like your modified code is
import java.util.Scanner;
public class cs21`enter code here`0 {
public static double weight;
public static double height;
public static double bmi;
public double wcal;
public double mcal;
public static double age;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
cs210 cs=new cs210();
method1 ();
double val=cs.method2 ();
double value1=cs.method3 (weight,age,height);
double value2=cs.method4 (weight,age,height);
cs.method5 (bmi,value1,value2);
}
public static void method1 () {
System.out.println ("This program implements a Health Assistance Calculator ");
System.out.println ("Given a weight, height, and age, it will compute:\n");
System.out.println ("BMI - Body Mass Index");
System.out.println ("Calories needed per day to maintain weight");
}
public double method2 () {
Scanner keyboard = new Scanner (System.in);
System.out.println ("Please enter your weight:");
weight = keyboard.nextDouble ();
System.out.println ("Press 1 if weight was entered in Kg \n Press 2 if weight was entered in Lbs");
double wunits = keyboard.nextDouble();
if (wunits == 1) {
System.out.println("Thank you");
} else if (wunits == 2){
weight = weight / 2.2;
System.out.println("Thank you");
}
else {
System.out.println ("Please try again");
return 0;
}
System.out.println("Please enter your height:");
height = keyboard.nextDouble ();
System.out.println ("Press 1 if height was entered in meters \n Press 2 if height was entered in inches");
int hunits = keyboard.nextInt();
if(hunits ==1) {
System.out.println("Thank you");
} else if (hunits == 2){
height = height / 0.0254;
}else {
System.out.println("Please try again");
return 0;
}
System.out.println("Please enter your age in years:");
age = keyboard.nextDouble ();
bmi = weight / Math.pow(height, height);
return ( bmi + age + height + weight);
}
public static double method3(double weight, double age, double height) {
double paf = 1.375;
double mcal;
mcal = (13.397 * weight + 4.799 * height + 5.677 * age + 88.362) * paf;
return mcal;
}
public static double method4(double weight, double age, double height){
double wcal;
double paf=1.375;
wcal = (93247 * weight + 3.098 * height - 4.330 * age + 447.593) * paf;
return wcal;
}
public void method5(double bmi, double mcal, double wcal){
System.out.println("Your BMI is:" + bmi);
System.out.println("A BMI in the range of 18.5 to 24.9 is considered normal\n");
System.out.println("To maintain your current weight:");
System.out.println("Men need" + mcal + "per day");
System.out.println("Women need" + wcal + "per day");
}
}
Actually to make your code work the way it is written you should:
make all the fields and methods static
remove parameters from all methods declarations
declare local variable paf in method4.
That being said the code in that form is quite ugly. You should think about the following improvements:
class name should start from capital letter
class name should be something meaningful (e.g. BcmCalculator)
fields should be private
method should have meaningful names ( printGreetings, readUsersAttributes, etc)
in main method you should create instance of the class and call its methods
paf should be a constant (ie field private static final double PAF = 1.375;).
There are further possible improvements, but this should be enough for the beginning.
While doing an assignment for a BMI calculator I keep running into problems with the compiler and the method being used.
The assignment requires me to call a function double bmi to calculate the bmi. I am having problems getting the calling of the function correct. Any help would be great.
One of the errors:
Prog5.java:44: error: illegal start of expression
public static double calculateBmi(double height, double total) {
^
Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double avgweight,bmi,total,wReading;
int heightft,heightin,height,k;
String category,weightreading;
System.out.print("Enter the height(in feet and inches separated by spaces): ");
heightft = sc.nextInt();
heightin = sc.nextInt();
height = ((heightft*12)+heightin);
System.out.print("Enter the weight values separated by spaces followed by a negative number: ");
wReading = sc.nextDouble();
While (wReading >=0);
{
total = wReading+total;
Count++;
wReading = sc.nextDouble();
}
avgweight = 0;
total = 0;
weightreading = "Weight readings: " + wReading;
avgweight = total/Count;
public static double calculateBmi(double height, double total) {
{
double bmi = 0;
double total = 0;
double height = 0;
bmi = (height*703) / (total*total);
}
return bmi;
}
if ( bmi > 30)
category=("Obese");
else if (bmi >= 25)
category=("Overweight");
else if (bmi >= 18.5)
category=("Normal");
else {
category=("Underweight");
}
System.out.println("");
System.out.println("Height: "+ heightft + " feet " + heightin + " inches" );
System.out.println("Weight readings: "+ count);
System.out.println("Average weight: " + avgweight + "lbs");
System.out.println("");
System.out.printf("BMI: " + "%.2f", bmi);
System.out.println("");
System.out.println("Category: " + category);
System.out.println("");
}
private static void ElseIf(boolean b) { }
private static void If(boolean b) { }
}
The problem you mention is due to you beginning another method inside main. You instead want a structure something like:
public class Prog5
{
public static void main(String[] args)
{
// code here
}
public static double calculateBMI(double height, double total)
{
//other code
}
}
Your problem is that you are attempting to define a method (namely, public static double calculateBMi) inside a method (public static void main), and Java does not let you do that. (Basically, methods that aren't main need to be attached to a class.)
In the future, you may want to look around before asking this kind of question, since duplicate versions of this have been asked. Your question is basically: Function within a function in Java