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.
Related
Rectangle
public class Rectangle {
private double width;
private double length;
public Rectangle(double L, double W){
length = L;
width = W;
}
public void setLength(double Length){
if (length>=0 && length <=20)
length = Length;
else{
length = 0;
}
}
public double getLength(){
return length;
}
public void setWidth(double Width){
if (width>=0 && length <=20)
width = Width;
else{
width = 0;
}
}
public double getWidth(){
return width;
}
public void calculatePerimeter(){
System.out.println("The perimeter of rectangle is: " + 2 * (length + width));
}
public void calculateArea(){
System.out.println("The area of the rectangle is: " + (length * width));
}
}
TestRectangle
import java.util.Scanner;
public class TestRectangle {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Rectangle myRectangle = new Rectangle (0,0);//I did the same thing in a
//previous assignment, and someone else who did this assignment (code found
//online) also did this. It worked before but seems useless now?
System.out.println("Enter length: ");
double L = input.nextDouble();
System.out.println();
System.out.println("Enter width: ");
double W = input.nextDouble();
System.out.println();
}
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();//and here is where I get the error
//<identifier> expected, package myRectangle does not exist
}
I am trying to create a program "Rectangle" to calculate the area and perimeter of a rectangle, and then create a test program to run program "Rectangle"
I have copied code from a previous assignment called "Date", where the basic idea is similar, but when I get to the end of the program where I need to call on "calculateArea();" and "calculatePerimeter();" in the test program, I get an error telling me that package myRectangle doesn't exist.... can someone tell me why this is happening? A similar code worked in the previous assignment, and I found someone else's code for the same "Rectangle" program and it shows the same error. Did I do something wrong or is there something wrong with my NetBeans?
This is the code I based the Rectangle and TestRectangle program off of
Date
public class Date {
private int month;
private int day;
private int year;
public Date(int m, int d, int y){
month = m;
day = d;
year = y;
}
public void setMonth(int Months){
if(Months>=0 && Months <= 12)
month=Months;
else{
month=0;
}
}
public int getMonth(){
return month;
}
public void setDay(int Days){
if(Days>= 0 && Days<=31)
day = Days;
else{
day=0;
}
}
public int getDay(){
return day;
}
public void setYear(int Years){
year=Years;
}
public int getYear(){
return year;
}
public void displayDate(){
System.out.printf
("%d/%d/%d\n", getMonth(), getDay(), getYear() );
}
}
TestDate
import java.util.Scanner;
public class DateTest {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Date myDate = new Date(0,0,0);
System.out.println("Justine Dodge, assignment 6\n");
System.out.println("Please enter month: ");
int m = input.nextInt();
myDate.setMonth(m);
System.out.println();
System.out.println("Enter day: ");
int d = input.nextInt();
myDate.setDay(d);//assign d to Day?
System.out.println();//output blank line
System.out.println("Enter year: ");
int y = input.nextInt();
myDate.setYear(y);
System.out.println();
myDate.displayDate();
}
}
in the TestRectangle you are closing the main method before calling these functions
} // this should be at at the end of the main function
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();//and here is where I get the error
i.e
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();//and here is where I get the error
}
This will remove the compilation error. Now when you run it , you will get both area and perimeter as 0 because in the constructor , you are passing values of length and width as 0 and not really using the length and width taken as input.
To resolve this issue, insstead of passing 0,0 in constructor,
try to pass L,W in constructor like this
Rectangle myRectangle = new Rectangle (L,W);
myRectangle.getLength()); //
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();
import java.util.Scanner;
public class TestRectangle {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
// Rectangle myRectangle = new Rectangle (0,0);//I did the same thing in a
//previous assignment, and someone else who did this assignment (code found
//online) also did this. It worked before but seems useless now?
System.out.println("Enter length: ");
double L = input.nextDouble();
System.out.println();
System.out.println("Enter width: ");
double W = input.nextDouble();
System.out.println();
Rectangle myRectangle = new Rectangle (L,W);
// System.out.println("get length " + myRectangle.getLength());
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();//and here is where I get the error
//<identifier> expected, package myRectangle does not exist
}
}
then you will get o/p like this
I'm currently writing a code that asks for a packages dimensions then uses the volume to calculate the shipping costs. There is another class that I have not included in the post which handles the cost calculation. I currently at a loss for how to take the input of the inputLength etc. methods and put them into the Package and Package copy methods. And also why i cant use them in the calcVolume and displayDimensions methods.
import java.util.Scanner;
public class Package {
private double length;
private double width;
private double height;
private Scanner input = new Scanner(System.in);
public Package() {
double length = 1.0;
double width = 1.0;
double height = 1.0;
}
public static void main(String[] args) {
System.out.printf("Welcome to Colin's Shipping Calculator!%n%n");
System.out.printf("Enter first package dimensions%n");
Package volCalc;
volCalc = new Package();
volCalc.inputLength();
volCalc.inputWidth();
volCalc.inputHeight();
System.out.printf("Enter second package dimensions%n");
volCalc.inputLength();
volCalc.inputWidth();
volCalc.inputHeight();
volCalc.displayDimensions();
volCalc.calcVolume();
Shipment shipCalc = new Shipment();
shipCalc.inputPackage();
shipCalc.inputPackage();
shipCalc.calculateCost();
shipCalc.display();
}
public Package(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
public Package(Package copy) {
Package newPackage = new Package();
newPackage.length = copy.length;
newPackage.width = copy.width;
newPackage.height = copy.height;
}
public void inputLength() {
System.out.printf("Enter Length: ");
double length = input.nextDouble();
}
public void inputWidth() {
System.out.printf("Enter Width: ");
double width = input.nextDouble();
}
public void inputHeight() {
System.out.printf("Enter Height: ");
double height = input.nextDouble();
}
public void displayDimensions() {
System.out.printf(length + " X " + width + " X " + height);
}
public double calcVolume() {
double volume = length*width*height;
System.out.printf("%nVolume: " + volume);
return volume;
}
You are shadowing your member variables by declaring them again in the methods. Try removing the 'double' before the variable name in the functions.
Here an example. I also changed every printf statement to either print or println. But I'm not sure how Shipment should work.
import java.util.Scanner;
public class Package {
private double length;
private double width;
private double height;
private Scanner input = new Scanner(System.in);
public Package() {
this.length = 1.0; // Removed 'double'
this.width = 1.0;
this.height = 1.0;
}
public static void main(String[] args) {
System.out.println("Welcome to Colin's Shipping Calculator!\n");
System.out.println("Enter first package dimensions");
Package packageA;
packageA = new Package();
packageA.inputLength();
packageA.inputWidth();
packageA.inputHeight();
packageA.displayDimensions();
packageA.calcVolume();
System.out.println("Enter second package dimensions");
Package packageB = new Package(); // New Package
packageB.inputLength();
packageB.inputWidth();
packageB.inputHeight();
packageB.displayDimensions();
packageB.calcVolume();
Shipment shipCalc = new Shipment();
shipCalc.inputPackage();
shipCalc.inputPackage();
shipCalc.calculateCost();
shipCalc.display();
}
public Package(double length, double width, double height) {
this.length = length; //'this' needed else shadowing occurs
this.width = width;
this.height = height;
}
public Package(Package copy) {
// Package newPackage = new Package(); Not needed
this.length = copy.length; // 'this' just for clarification.
this.width = copy.width;
this.height = copy.height;
}
public void inputLength() {
System.out.print("Enter Length: ");
length = input.nextDouble(); // Removed 'double'
}
public void inputWidth() {
System.out.print("Enter Width: ");
width = input.nextDouble(); // Removed 'double'
}
public void inputHeight() {
System.out.print("Enter Height: ");
height = input.nextDouble(); // Removed 'double'
}
public void displayDimensions() {
System.out.println(length + " X " + width + " X " + height);
}
public double calcVolume() {
double volume = length * width * height;
System.out.println("Volume: " + volume);
return volume;
}
}
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();
}
}
I am a beginner in Java and my professor wants us to create a program that involves some math. The thing is that he wants the calculations in a separate method. Can someone please help me. The program will not run the result for some reason. I tried looking around this website and could not find the answer. Here is the code below:
import javax.swing.JOptionPane;
public class forFun {
public static void main(String[] args)
{
double x, y, z;
String xVal, yVal, zVal;
xVal = JOptionPane.showInputDialog("Enter first integer: ");
yVal = JOptionPane.showInputDialog("Enter second integer: ");
zVal = JOptionPane.showInputDialog("Enter third integer: ");
x = Double.parseDouble(xVal);
y = Double.parseDouble(yVal);
z = Double.parseDouble(zVal);
System.exit(0);
}
public static void sumOfStocks(double x, double y, double z)
{
double result = x * y * z;
System.out.println("The product of the integers is: " + result);
System.exit(0);
}
}
Here is the example of how the code should be
import javax.swing.JOptionPane;
public class forFun {
public static void main(String[] args)
{
double x, y, z;
String xVal, yVal, zVal;
xVal = JOptionPane.showInputDialog("Enter first integer: ");
yVal = JOptionPane.showInputDialog("Enter second integer: ");
zVal = JOptionPane.showInputDialog("Enter third integer: ");
x = Double.parseDouble(xVal);
y = Double.parseDouble(yVal);
z = Double.parseDouble(zVal);
double result = sumOfStocks(x, y, z);
System.out.println("The result is %d", result);
System.exit(0);
}
public static double sumOfStocks(double x, double y, double z)
{
double result = x * y * z;
return result;
}
}
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);
}