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();
}
}
Related
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
So i'm new to java, we just started this language in my programming class about a month ago. Anyhow, we're on overloading methods right now (just started methods last week) and I'm having trouble with comparing the values of the return statements in the overloaded methods. My intention is to compare them in an if statement in the main method. I'm sure the answer is simple, but i can't find information on it in my textbook or online. Sorry about the sloppy indentation, I'm having trouble with the features on this website and it's the first time i've used it. would appreciate any help! Here is the program:
import java.util.Scanner;
public class pizzaCalculation {
public static void main(String[] args){
//create scanner
Scanner i = new Scanner(System.in);
//create sentinel while loop, initiate priceperinch for both pizzas
int sentinel = 1;
//create while loop
while(sentinel != 0){
//create input for round pizza
System.out.println("What is the price of the round pizza?");
double priceRound = i.nextDouble();
System.out.println("What is the radius?");
double radius = i.nextDouble();
pizzaPrice(radius, priceRound);
System.out.println("What is the price of the rectangular pizza?");
double priceRect = i.nextDouble();
System.out.println("What is the width and length of the rectangular pizza?");
double width = i.nextDouble();
double length = i.nextDouble();
pizzaPrice();
//create if statement to determine best deal
if (pricePerInchRound > pricePerInchRect){
System.out.println("The best deal is the round pizza which is $"+pricePerInchRound);
}else{
System.out.println("The best deal is the rectangular pizza is $"+pricePerInchRect);
}
//ask if user would like to do again
System.out.println("Would you like to do another calculation? Enter 1 for yes and 0 for no.");
sentinel = i.nextInt();
}
}
public static double pizzaPrice(double num1, double priceRound){
Scanner i = new Scanner(System.in);
//this is for round pizza
double areaRound = Math.PI * num1 * num1;
double pricePerInchRound = priceRound / areaRound;
return pricePerInchRound;
}
public static double pizzaPrice(double num1, double num2, double priceRect){
//this is for rectangular pizza
//create scanner
Scanner i = new Scanner(System.in);
double areaRect = num1 * num2;
double pricePerInchRect = priceRect / areaRect;
return pricePerInchRect;
}
}
So there are several issues:
You need to pass parameters to the second call of pizzaPrice() like this
pizzaPrice(width, length, priceRect);
You need to store results of method calls in variables like
pricePerInchRound = pizzaPrice(a, b);
pricePerInchRect = pizzaPrice(a, b, c);
You are calling pizzaPrice() but you need to store the resulting value in a variable so you can use it later (and pass the right parameters).
double pricePerInchRound = pizzaPrice(radius, priceRound);
and ...
double pricePerInchRect = pizzaPrice(width, length, priceRect);
Also, take care to name your method parameters better - num1, num2 aren't very descriptive. You could have used width, length.
I'm writing a program that takes the users input for height and weight then calculates the Body Mass Index from this. It uses separate methods for height, weight and BMI, these methods are called from main. The problem I'm having is I have absolutely no clue how to put the input from weight and height methods into the BMI method. This is what the code looks like:
public class BMIProj {
static Scanner input = new Scanner(System.in);
public static int heightInInches()
{
System.out.println("Input feet: ");
int x;
x = input.nextInt();
System.out.println("Input Inches: ");
int y;
y = input.nextInt();
int height = x * 12 + y;
return height;
}
public static int weightInPounds()
{
System.out.println("Input stone: ");
int x;
x = input.nextInt();
System.out.println("Input pounds ");
int y;
y = input.nextInt();
int weight = x * 14 + y;
return weight;
}
public static void outputBMI()
{
}
public static void main(String[] args) {
heightInInches();
weightInPounds();
outputBMI();
}
Thanks in advance.
I advise you to do a little bit more learning in java, specifically variables, declaring, initializing, etc.. Also learn class, constructors, etc..
You need fields for the class to save the inputed variables
I created a constructor to initialize the variables
You don't need to return anything in the methods if all you are doing is assigning values to your class fields and outputting info.
I did the curtsy of calculating the bmi for you
Anyway
public class BMIProj {
static Scanner input = new Scanner(System.in);
// Class vars
int height;
int weight;
double bmi;
//Constructor
public BMIPrj(){
//Initialize vars
height = 0;
weight = 0;
bmi = 0;
}
public static void heightInInches()
{
System.out.println("Input feet: ");
int x;
x = input.nextInt();
System.out.println("Input Inches: ");
int y;
y = input.nextInt();
int height = x * 12 + y;
return height;
}
public static void weightInPounds()
{
System.out.println("Input stone: ");
int x;
x = input.nextInt();
System.out.println("Input pounds ");
int y;
y = input.nextInt();
int weight = x * 14 + y;
return weight;
}
public static void outputBMI()
{
System.out.println("BMI: " + (( weight / height ) x 703));
}
public static void main(String[] args) {
heightInInches();
weightInPounds();
outputBMI();
}
You can assign the output of a method to a parameter like so:
int weight = weightInPounds();
When calling a method, you can pass in parameters:
outputBMI(weight);
The rest is up to you.
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.
I need to be able to input length and width of a rectangle into a console and calculate its perimeter and area. I have it working other than accepting my inputs for the calculations. I know I'm close, but can't seem to figure it out. Thanks in advance for your help. Keep in mind I'm a novice to put it nicely, so your answers may not make sense to me at first. I cannot get it to calculate the values that I input into the console.
package edu.purdue.cnit325_lab1;
public class Rectangle {
private static double length;
private static double width;
public Rectangle() {
length=0.0;
width=0.0;
}
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double FindArea() {
return length*width;
}
public double FindPerim() {
return length*2 + width*2;
}
}
package edu.purdue.cnit325_lab1;
import java.util.Scanner;
public class TestRectangle {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanL = new Scanner (System.in);
System.out.print("Please enter the length of the rectangle: ");
double L = scanL.nextDouble();
Scanner scanW = new Scanner (System.in);
System.out.print("Please enter the length of the rectangle: ");
double W = scanW.nextDouble();
//int W = scanW.nextInt();
double RectangleArea;
Rectangle unitRectangle = new Rectangle();
RectangleArea = unitRectangle.FindArea();
System.out.println("The area of a unit rectangle is " + RectangleArea);
double RectanglePermiter;
Rectangle perimRectangle = new Rectangle();
RectanglePermiter = perimRectangle.FindPerim();
System.out.println("The permimiter of the unit rectangle is " + RectanglePermiter);
}
}
Note that you are calling the Rectangle constructore with no arguments thus setting its width and height to zero, you should use
Rectangle unitRectangle = new Rectangle(L,W);
and indeed like the other answer you should use one Scanner instance.
Plus regarding coding style: do not upercase your variable names. Its quite confusing for more "experienced" java developers. :-)
you missed to call parameterized constructor.
public static void main(String[] args) {
Scanner scanL = new Scanner (System.in);
System.out.print("Please enter the length of the rectangle: ");
double L = scanL.nextDouble();
System.out.print("Please enter the length of the rectangle: ");
double W = scanL.nextDouble();
Rectangle rectangle = new Rectangle(l,w);
double rectangleArea = rectangle .FindArea();
System.out.println("The area of a unit rectangle is " + rectangleArea);
double rectanglePermiter = rectangle.FindPerim();
System.out.println("The permimiter of the unit rectangle is " + rectanglePermiter);
}
Note: Unnecessarily you created two Scanner objects and two Rectangle objects in your code,which are removed from the above code.
Use one Scanner instance. Just reuse it.
Scanner scanner = new Scanner (System.in);
System.out.print("Please enter the length of the rectangle: ");
double L = scanner.nextDouble();
System.out.print("Please enter the length of the rectangle: ");
double W = scanner.nextDouble();
Update: You don't pass the L and W to the constructor as the other answer points out. However, some mistakes you made:
You declared length and width as static. Don't do that. That makes no sense. The length and the width are properties of a rectangle and shouldn't be shared by all rectangle instances.
You don't use the correct naming conventions: variables start with a lowercase character, class names start with an uppercase character.
You are creating two instances of your Rectangle to calculate both perimeter and area of the same rectangle. Share that instance instead.
So you need to set the values in some way... you can do either
A)
Rectangle unitRectangle = new Rectangle(l,w);
B)
or create getters and setters in the rectangle class..
setLength(double l) length = l;
setWidth(double w) width = w
double getLength() return length;
double getWidth() return height;
Since you are initializing with the default constructor
aka
Rectangle unitRectangle = new Rectangle();
the values for length and width will also be zero.
Your code consists of the Default constructor, which will initialize the respective values length and width to 0.0 as set by you and also consist of parametrized constructor which requires input values to be provided and will set the value accordingly.
When you are creating the object of your class, you are calling the Default Constructor instead of parametrized constructor in this line
Rectangle unitRectangle = new Rectangle();
Thus setting them to 0.0
If you do Something like this
Rectangle unitRectangle2 = new Rectangle(2.3,4.3);
This will create the object having values for length and breadth as 2.3 and 4.3 respectively.
//write a java program which will calculate area and perimeter of rectangle by accepting radius from cmd prompt
//area = width x height,perimeter = (2 x width) + (2 x height)
class AreaAndPerOfRect
{
int h,w;
void set(int x,int y)
{
h=x;
w=y;
}
int AreaOfRect()
{
int area=w*h;
return area;
}
int PerOfRect()
{
int per=(2*w)+(2*h);
return per;
}
void disp()
{
int area=AreaOfRect();
System.out.println("area of rectangle"+area);
int per=PerOfRect();
System.out.println("area of rectangle"+per);
}
}
class AreaAndPerOfRectDemo
{
public static void main(String args[])
{
if(args.length!=2)
{
System.out.println("please enter two values");
}
else
{
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
AreaAndPerOfRect ap=new AreaAndPerOfRect();
ap.set(x,y);
ap.disp();
}
}
}
//This is the Java code for finding the area and perimeter of a rectangle
package demo;
import java.util.Scanner;
public class DemoTranslation {
public static int area(int length, int width) {
int areaOfRectangle;
areaOfRectangle = length * width;
System.out.println("Area of Rectangle is : " + areaOfRectangle);
return 0;
}
public static int perimeter(int length, int width) {
int perimeterOfRectangle;
perimeterOfRectangle = (length + width) * 2;
System.out.println("Perimeter of Rectangle is : " + perimeterOfRectangle);
return 0;
}
public static void main(String[] args) {
int length, width, choice;
System.out.println("Enter the length of the triangle ");
length = STDIN_SCANNER.nextInt();
System.out.println("Enter the width of the triangle ");
width = STDIN_SCANNER.nextInt();
System.out.println("Enter 1 : View the area ");
System.out.println("Enter 2 : View the perimeter ");
System.out.println("Enter 3 : view both ");
choice = STDIN_SCANNER.nextInt();
switch(choice) {
case 1:
area(length, width);
break;
case 2:
perimeter(length, width);
break;
case 3:
area(length, width);
perimeter(length, width);
break;
default:
System.out.println("Invalid option ");
break;
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}