Calling an object from different classes - java

I have a main class to run a BMI calculator class which calculates BMI info (body mass index) with fields for name, age, sex, height, and weight.
There is also a WaistToHip calculator class to calculate waist-to-hip ratio with fields
waist and hip.
However, when I wanted to create a
BodyFat calculator I need the height and waist from both classes.
How am I suppose to call these in my body fat calculator class for my formula?
public class body_fat_calculation {
private double neck;
private double CBF;
waist_to_hip_ratio waist;
bmiCalculator height;
public body_fat_calculation(double neck) {
super();
this.neck = neck;
}
public double getCBF() {
return CBF;
}
public void setCBF(double cBF) {
CBF = cBF;
}
public double getNeck() {
return neck;
}
public void setNeck(double neck) {
this.neck = neck;
}
public double Round(double Rval, int Rpl){
double p = Math.pow(10, Rpl);
Rval=Rval*p;
double tmp = Math.round(Rval);
return tmp/p;
}
public void calculateWTHR(){
CBF= Round((495/(1.0324 - 0.19077 * Math.log10((waist)-(neck)) + 0.15456 * Math.log10(height)) - 450),2);
}
}

Why don't you do something like this? If you notice I have added two parameters to the BodyFatCalculator class - waist and height.
public class Main {
public static void main(string[] args){
// I assume you will want to use a scanner to get user input to set these variables dynamically
// for the sake of the example, I have set them myself.
double height = 1.82; // meters
double weight = 170.0;
double waist = 35.0;
double hip = 40.0;
double neck = 7.1;
String name = "Dave";
String sex = "M";
int age = 20;
// create new BMI Calculator to figure out body mass index
BMICalculator bmiCalc = new BMICalculator(name, age, sex, height, weight);
double bmi = bmiCalc.calculateBmi(); // calculate body mass index
WaistToHipCalculator waistHipCalc = new WaistToHipCalculator(waist, hip);
double whr = waistHipCalc.calculateWhr(); // calculate waist to hip ratio
BodyFatCalculator bfCalc = new BodyFatCalculator(neck, height, waist);
double bf = bfCalc.calculateBf(); // calculate body fat
// print results
}
}

Classes are more nouns. A verb should be a method. With a class called BodyFatCalculation I think you're trying too hard to use a lot of classes. Just have a Body (noun) class with calculateBodyMassIndex and calculateBodyFat (verbs) as methods. You could create a Dimensions class with height and waist in it (with getters and setters as needed) and keep an instance of that inside the Body class, but that's overkill here.

Related

Undefined Constructor Java

I wrote a small program which has three classes: Carpet, Calculator and Floor.
The carpet class will be called to be multiplied with the floor class by using the calculator class in the main. However, I found that when using double as a return type in the calculator class I came across constructor undefined error.
I found out to be the issue of the calculator class I have a method getTotalCost() to return the cost of floor and carpet. why can't I just pass two objects as a parameter in calculator when called in main. I used primitive return type of double in calculator class.
Please help me rewrite the calculator class and explain to me why I can't use the primitive types class but instead, I must use the class name in the calculator field declaration of floor and carpet. Why must the class name for floor and carpet to be passed into the constructor in order to build the object? What is the fix in getTotalCost() as if you use the class name to declare two instance fields then surely the error will be something like this:
- The operator * is undefined for the argument
type(s) Floor, Carpet
- Occurrence of 'carpet'
- 1 changed line
Trying to use the classes created but received an error.
Carpet carpet = new Carpet(3.5);
Floor floor = new Floor(2.75, 4.0);
passing floor and carpet in the parameter of calculator.
//constructor not defined Calculator calculator = new Calculator(floor,carpet);
public class Calculator {
private double floor;
private double carpet;
public Calculator()
{
}
public Calculator(double floor, double carpet) {
this.carpet=carpet;
this.floor=floor;
}
public double getTotalCost()
{
return (this.floor*this.carpet);
}
}
public class Floor {
private double width;
private double length;
public Floor()
{
}
public Floor(double width,double length)
{
this.length=length;
this.width=width;
}
public void setWidth(double width)
{
if (this.width < 0) {
this.width=0;
}
else {
this.width=width;
}
}
public void setLength(double length)
{
if (this.length < 0) {
this.length=0;
}
else {
this.length=length;
}
}
public double getArea()
{
return (this.length * this.width);
}
}
public class Carpet {
private double cost;
public Carpet()
{
}
public Carpet(double cost)
{
this.cost=cost;
}
public void setCost(double cost)
{
if (cost < 0) {
this.cost=0;
}
else {
this.cost=cost;
}
}
public double getCost()
{
return this.cost;
}
}
Since your Calculator class has only the default constructor (one without any args) and a constructor that only accepts double, double, you can't create a Calculator instance providing a Carpet instance and a Floor instance.
So you have 2 options:
Pass the floor area and carpet cost to the current constructor.
Calculator calculator = new Calculator(floor.getArea(), carpet.getCost());
Change the constructor to accept a Carpet instance and a Floor instance (then your Calculator class logic also should be modified)
public class Calculator {
private Floor floor;
private Carpet carpet;
public Calculator() {
}
public Calculator(Floor floor, Carpet carpet) {
this.carpet=carpet;
this.floor=floor;
}
public double getTotalCost()
{
return (this.floor.getArea() * this.carpet.getCost());
}
}
The parameters of the Calculator class is (double, double) so it will not accept Floor and Carpet objects. You can either call the constructor like:
Calculator calc = new Calculator(carpet.getCost(), floor.getCost());
Or change the constructor to the following:
Calculator (Floor f, Carpet c) {
this.floor = f.getCost();
this.carpet = c.getCost();
}
You cannot multiply objects. Looks, like you wand to multiply carpet on a floor and get... Something? This is not working like this, think about it a little deeper - the fact is you really want to multiply the carpet square (number of square meters to be more specific) on cost of 1 square meter (number of currency). When you understand this, you should have no trouble to correct your code, so the Calculator would haveFloorandCarpet` fields and be able to calculate total cost based on floor square and carpet cost #Udith Gunaratna answered

Testing my program?

I already have the class I need to implement in to my code. The instructions are: Code a testing program/class. This should construct or instantiate objects of the class you coded in step #1. Your testing program should call every method to make sure they work. You should construct at least two objects – one with the default constructor and one with the “other” constructor. For the second scenario, ask the user what values for (radius and) height. You may use any input and output that you want for this.
This is what I have so far and I'm stuck:
public class Cube
{
private double height;
public Cube(){
height = 1.0;
}
public Cube(double h){
height = h;
}
public double getHeight(){
return height;
}
public void setHeight(double h){
height = h;
}
public double calcVolume() {
return height*height*height;
}
public double calcSurface(){
return height*height*6;
}
public String toString(){
return this.toString();
}
public boolean equals(Cube c){
return (c.getHeight() == this.height);
}
}
import java.util.*
public class TestTheCube
{
public static void main(String[] args)
{
Cube cube1 = new Cube();
Scanner kb = new Scanner(System.in);
System.out.print("Enter a height as a positive number");
double height = kb.nextDouble();
Cube cube2 = new Cube(height);
System.out.println(
}
}
I've invoked calcVolume() of cube1 and cube2.
Cube cube1 = new Cube();
Scanner kb = new Scanner(System.in);
System.out.print("Enter a height as a positive number");
double height = kb.nextDouble();
Cube cube2 = new Cube(height);
System.out.println("Cube 1's volume = "+cube1.calcVolume());
System.out.println("Cube 2's volume = "+cube2.calcVolume());
.....//repeat for every instance method you have.

Java: How to put the value of a user defined attribute into an array?

For example, if this is my class...
public class Person {
private double height; //Height in inches
//constructors
public Person(double newHeight) {height = newHeight;}
public Person() {}
//Getter
public double getHeight() {return height;}
//Setter
public void setHeight(double newHeight) {height = newHeight;}
}
and then this is my driver...
import javax.swing.JOptionPane;
class Myclass {
public static void main{String[] args) {
String userInput;
int arraylen;
Person bob = new Person ();
double[] myarray;
userInput = JOptionPane.showInputDialog("How many heights do you have
to list?");
arraylen = Integer.parseInt(userInput);
myarray = new double[arraylen];
for(int i=0;i<myarray.length;i++) {
userInput = JOptionPane.showInputDialog("What is the next height?");
bob.setHeight(Double.parseDouble(userInput));
// I need something here to put that attribute value into the array.
}
}
}
So at this point I have a value in the height attribute and I need to figure out how to move that into an array. I'm sure putting user input into an attribute to just then move it to an array probably isn't the best way to do this, but it's for school, so it's what I need to figure out. Please share any suggestions of better ways to do it though. However, I'm mainly concerned with how to do it like this.
What you seem to want to do, setting the height of bob to a value, and then setting the entry in an array to the height of bob, can be done by adding the line:
myarray[i] = bob.getHeight();
to the end of your for loop.

Classes and Objects. Getting 0.0 as answer when calculating price. - JAVA

I'm working out a question from a labsheet but i'm only getting 0.0 as answer when running the program. I can't find out what's wrong please help.
The question:
Implement a class Pizza with attribute diameter (in cm), cost_sq_cm (cost per square cm) and area. Its methods are:
• Constructor to create an object of type Pizza with a given diameter and given price_sq_cm.
• Mutator and accessor methods for diameter and cost_sq_cm.
• calcArea to calculate the area of a given pizza.
• getPrice to calculate and return the price of a pizza.
Write a class TestPizza with a main method that declares an object of type Pizza with a user inputted diameter and user-­‐inputted cost_sq_cm of a circular pizza, and display the price of the pizza.
The Pizza class:
package Number3;
public class Pizza {
private int diameter;
private float cost_sq_cm;
private double area;
private double price;
public Pizza() //default constructor
{
diameter = 0;
cost_sq_cm = 0;
area = 0;
price = 0;
}
public Pizza(int d,float cost,double a,double p) //overloaded constructor
{
d = diameter;
cost = cost_sq_cm;
a = area;
p = price;
}
public void Constructor() //method
{
Pizza P = new Pizza();
}
public void setDiameter(int d) //mutator
{
d = diameter;
}
public int getDiameter() //accessor
{
return diameter;
}
public void setCost(float c)
{
c = cost_sq_cm;
}
public float getCost()
{
return cost_sq_cm;
}
public double calcArea()
{
area = 3.142 * (diameter * diameter);
return area;
}
public double getPrice()
{
price = area * cost_sq_cm;
return price;
}
public void display()
{
System.out.print("The area is: "+this.price);
}
}
TestPizza:
package Number3;
import java.util.Scanner;
public class TestPizza {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
float area = 0;
Pizza P = new Pizza();
int d; float c,a = 0;
System.out.print("Enter a value for the diameter: ");
d = input.nextInt();
P.setDiameter(d);
System.out.print("Enter a value for the cost: ");
c = input.nextFloat();
P.setCost(c);
P.display();
}
}
I'm new to JAVA. Please be lenient.
You should multiply cost per square centimeter times area to get price. You'll get zero if either one is equal to zero. I see where you've set diameter, but not area.
You set diameter, but you don't calculate area when you set it.
public void setDiameter(int d) //mutator; lose this comment. worthless clutter.
{
d = diameter;
area = calcArea();
}
I'd recommend following the Java idiom. Don't write a display() method; better to override toString().
I'd write it this way:
package cruft;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* Pizza
* #author Michael
* #link https://stackoverflow.com/questions/28658669/classes-and-objects-getting-0-0-as-answer-when-calculating-price-java
* #since 2/22/2015 12:27 PM
*/
public class Pizza {
private static final int DEFAULT_DIAMETER = 38;
private static final double DEFAULT_COST = 15.0;
private static final double DEFAULT_COST_PER_AREA = 0.013226; // 15 euro for a 38 cm diameter pizza
private static final NumberFormat DEFAULT_FORMAT = new DecimalFormat("#.####");
private final int diameter;
private final double costPerArea;
private final double price;
public static void main(String[] args) {
int diameter = ((args.length > 0) ? Integer.valueOf(args[0]) : DEFAULT_DIAMETER);
double costPerArea = ((args.length > 1) ? Double.valueOf(args[1]) : DEFAULT_COST_PER_AREA);
Pizza pizza = new Pizza(diameter, costPerArea);
System.out.println(pizza);
}
public Pizza(int diameter, double costPerArea) {
if (diameter <= 0) throw new IllegalArgumentException("diameter must be positive");
if (costPerArea <= 0) throw new IllegalArgumentException("cost per area must be positive");
this.diameter = diameter;
this.costPerArea = costPerArea;
this.price = this.costPerArea*this.calculateArea();
}
public double getPrice() {
return price;
}
private double calculateArea() {
return Math.PI*this.diameter*this.diameter/4.0;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Pizza{");
sb.append("diameter=").append(diameter);
sb.append(", costPerArea=").append(DEFAULT_FORMAT.format(costPerArea));
sb.append(", price=").append(NumberFormat.getCurrencyInstance().format(getPrice()));
sb.append('}');
return sb.toString();
}
}
For setting a field or another value it is
variable = value;
so
diameter = d;
It looks like your setCost and setDiameter methods need to be changed,
From
d = diameter;
To
this.diameter = d;
Instead of:
System.out.print("The area is: "+this.price);
Use:
System.out.print("The area is: "+this.getPrice());
You need to calculate area as well. So in your main method call it like:
P.calcArea();//to calculate area
You initialised price as 0, when you called new Pizza() and you never called getPrice which is where you calculate the price.
Also change your setter for cost from:
public void setCost(float c) {
c = cost_sq_cm;
}
To
public void setCost(float c) {
cost_sq_cm = c;
}

Why is my constructor not working?

I'm struggling with my my class constructor for a Java class I'm taking. Essentially, we're creating a Trapezoid class that takes in three double variables as arguments. Here is what my class-wide variables and constructor looks like:
public class Trapezoid
{
double height;
double longer;
double shorter;
public Trapezoid(double heightofTrapezoid, double longerSide, double shorterSide)
{
heightofTrapezoid = height;
longerSide = longer;
shorterSide = shorter;
}
However, when I try to create a Trapezoid object in my driver class, and print out the values, It's returning 0's for each variable. Here is my driver class:
public class TrapezoidApp
{
public static void main(String[] args)
{
// Arbitrary test values
final double height = 10.0;
final double longer = 5.5;
final double shorter = 7.25;
// Calculated offline from the above test values, used to verify code
final double area = 63.75;
// Instantiate a trapezoid object so that we can test it
Trapezoid t = new Trapezoid(height, longer, shorter);
double calculatedArea = t.getArea();
// Our "test" is to display the received values next to the expected
// values and verify that they match visually
System.out.println("All of the following numbers should match:");
System.out.println();
System.out.println(" Expected Received");
System.out.println(" -------- --------");
System.out.printf("Height:%8.2f %8.2f\n", height, t.getHeight());
System.out.printf(" Long:%8.2f %8.2f\n", longer, t.getLongerSide());
System.out.printf(" Short:%8.2f %8.2f\n", shorter, t.getShorterSide());
System.out.printf(" Area:%8.2f %8.2f\n", area, t.getArea());
}
}
Could I get some help with this? Thanks so much.
Assignment is right to left.
This
heightofTrapezoid = height;
should be
height = heightofTrapezoid;
Same for the other fields.
double height;
double longer;
double shorter;
public Trapezoid(double heightofTrapezoid, double longerSide, double shorterSide)
{
height = heightofTrapezoid;
longer = longerSide;
shorter = shorterSide;
}
As mentioned above, the problem is with assignments and I would suggest you learn to use the this keyword inside your constructor.
public Trapezoid(double heightofTrapezoid, double longerSide, double shorterSide)
{
this.height = heightofTrapezoid;
this.longer = longerSide;
this.shorter = shorterSide;
}

Categories

Resources