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
Related
I'm new to Java programming and having a hard time understanding the use of methods and how to use them in the code. I know this is really basic things and I'm trying, it's just hard to grasp at first. So tl;dr I don't quite understand this error or how to fix it.
public class TriangleInfo {
public static void main(String args[]) {
Triangle versuch = createTriangle();
}
public static createTriangle() {
double side1 = 90;
double side2 = 80;
double hypotenuse = getHypotenuse();
Triangle thisTriangle = new Triangle(side1, side2, hypotenuse);
return thisTriangle;
}
public static double getHypotenuse() {
return Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2));
}
}
The error I'm getting is:
The method createTriangle() is undefined for the type TriangleInfo
I also have this written in another file:
public class Triangle {
double side1;
double side2;
double hypotenuse;
// Konstrukturen
public Triangle(double sideOne, double sideTwo, double hypotenuse) {
this.sideOne = sideOne;
this.sideTwo = sideTwo;
this.hypotenuse = hypotenuse;
}
}
Could someone please help me understand this error and how to correct it? Thank you!
The error is that your method createTriangle() doesn't have a return type. Since you are returning a Triangle, you need to add that.
public static Triangle createTriangle() {
And continue with your normal code.
Also, a good catch from #JO3-W3B-D3V, the side1 and side2 are not globally accessible in the class, so you need to do:
public static double getHypotenuse(double side1, double side2) {
return Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2));
}
So, your complete createTriangle() function becomes:
public static Triangle createTriangle(){
double side1 = 90;
double side2 = 80;
double hypotenuse = getHypotenuse(side1, side2);
Triangle thisTriangle = new Triangle(side1, side2, hypotenuse);
return thisTriangle;
}
Okay, first of all, looking at the code you've provided, the method createTriangle does not have a return type specified, all you need to do here is refactor it like so:
public static Triangle createTriangle() { // Body of the method...
Then there's the matter of the getHypotenuse method, since it has no reference to the values side1 or side2, you need to either alter it such that the these variables are properties within the class, or you can update the method & the caller, like so:
Caller
double hypotenuse = getHypotenuse(side1, side2);
Method
public static double getHypotenuse(double side1, double side2) { // Body of the method...
Finally, in the Triangle class, you have the property names stated as side, but in the constructor of the Triangle class, you try to assign this.sideOne, it should either be side1 in the constructor, or you should change the name(s) of the class properties.
Summary
To be fair, I appreciate that you're a beginner & to be fair, you weren't too far from having a working implementation.
Complete Solution
import java.lang.Math;
public class TriangleInfo {
public static void main(String args[]) {
Triangle versuch = createTriangle();
}
public static Triangle createTriangle() {
double side1 = 90;
double side2 = 80;
double hypotenuse = getHypotenuse(side1, side2);
Triangle thisTriangle = new Triangle(side1, side2, hypotenuse);
return thisTriangle;
}
public static double getHypotenuse(double side1, double side2) {
return Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2));
}
}
class Triangle {
double side1;
double side2;
double hypotenuse;
// Konstrukturen
public Triangle(double sideOne, double sideTwo, double hypotenuse) {
this.side1 = sideOne;
this.side2 = sideTwo;
this.hypotenuse = hypotenuse;
}
}
For my assignment, I have been asked to create a test harness which provides feedback on whether the following sums are true. For this question, I will only provide one sum as an example. I have been asked to produce the following:
TestCalculator has a method called testParser() which:
Tests that x("12 + 5") returns a Double with the value 17
I have been given a template in which to set this out on which looks like this:
Template
public class TestCalculator {
Double x;
/*
* Adds the parameter x to the instance variable x and returns the answer as a Double.
*/
public Double x(Double x){
System.out.println("== Adding ==");
//Sum here
return new Double(0);
}
public void testParsing() {
if (//condition) == 17) {
System.out.println("Adding Success");}
else {
System.out.println("Adding Fail");
}
}
And this is what I've managed to come up with so far:
Current program...Main class
public class Main {
public static void main(String[] args) {
TestCalculator call = new TestCalculator();
call.testParsing();
}
}
TestCalculator class
public class TestCalculator {
Double x;
Double doubleObject = 1.0;
/*
* Adds the parameter x to the instance variable x and returns the answer as a Double.
*/
public Double x(Double x){
System.out.println("== Adding ==");
this.x = 12.0;
x = 5.0;
return new Double(0);
}
public void testParsing() {
if (x(doubleObject) == 17) {
System.out.println("Adding Success");}
else {
System.out.println("Adding Fail");
}
}
}
I have two main queries. Firstly, I have been asked to test if "x("12 + 5") returns a Double with the value 17". I can see that this has been laid out so that the sum is a data type of String and I am confused as to why or how you would perform this calculation using the string data type.
Secondly, Within my current version of the program, the output returns that the adding calculation failed because I cannot access the returned double value of the calculation. But I am unsure of how I would access that value in my if statement and also return the output of the calculation and put it into the Double value that is returned in the method.
I have tried to make the question as clear and concise as possible for the reader to understand, any help on this would be greatly appreciated, thanks.
to return a new value that adds two values consider
public Double x(Double x){
System.out.println("== Adding ==");
//Sum here
this.x = x;
return new Double(x + 5);
}
Called as
if (x(12.0) == 17.0) {
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.
Create a program which simulates a very simple calculator
So I have been asked to implement an abstract class that represents binary (having 2 arguments) arithmetic expression
abstract class ArithmeticExpression {
double binary1;
double binary2;
public abstract void evaluate ();
public abstract void display ();
}
so then I created sub classes add, multiply, subtract, and divide. In subtract I have:
public class subtract extends ArithmeticExpression {
// private double result;
double binary1;
double binary2;
public subtract (double x, double y) {
this.binary1 = x;
this.binary2 = y;
}
public void evaluate () {
System.out.println("Expression: " + getsubX() + " - " + getsubY() + " = ");
// return result;
}
public void display () {
}
public double getsubX() {
}
public double getsubY() {
}
Using the classes I should be able to represent any arbitrary expression, with no hard coding.
It is also said evaluate should return the result as double and display method should print the expression out in string. Am I on the right track? What am I missing here? The part I do not understand how it is able to represent any expression?
Using your abstract ArithmeticExpression, here's what the Subtract class should look like. Java classes start with a capital letter.
public class Subtract extends ArithmeticExpression {
double result;
public Subtract(double x, double y) {
this.binary1 = x;
this.binary2 = y;
}
#Override
public void evaluate() {
result = binary1 - binary2;
}
#Override
public void display() {
System.out.println("Expression: " + binary1 +
" - " + binary2 + " = " + result);
}
}
You don't have to re-declare binary1 and binary2. They are instantiated in the abstract ArithmeticExpression class.
You do have to provide a double for the result. This should have been done in the abstract ArithmeticExpression class.
The evaluate() method is for evaluation.
The display() method is for display.
You don't have to define any other methods in your Subtract concrete class.
If you want to evaluate any expession inserted in form of
4 + 3 * ( 4 + 5)
You either need to create binary tree or stack and fill those values and operators in.
What I quite dont understand is your so called binary represented in double. If you want to have binary calc, you should use unsigned int or long (or any other type, that is not floating point)
Well, I need to make a project where I have two interfaces and they are both used in two unrelated classes. I managed to get everything else to work out properly except for the compareTo method. The two classes I have made are Car and Horse. What I am trying to do is compare the milesGoal from Horse to the one in Car and return either a 1, 0, or -1.
However when I try doing this I get the error "double could not be dereferenced"
I have been stuck on this for a while trying to find different ways to approach this part of the code. I tried using compareTo in the tester class instead of making a method but I got the same error and I am required to make it into a method.
This is the Horse Class:
public class Horse implements milesInterface , kilometersInterface{
private double currentMile;
private double currentKilo;
private double milesGoal;
private double kilosGoal;
private String horseBreed;
// CONSTRUCTORS
public Horse(){
currentMile = 0;
currentKilo = 0;
milesGoal = 0;
kilosGoal = 0;
horseBreed = "Unspecified";
}
public Horse(double cm, double ck, double mg, double kg, String hb){
currentMile = cm;
currentKilo = ck;
milesGoal = mg;
kilosGoal = kg;
horseBreed = hb;
}
// MILE METHODS
public double remainingMiles(){ // Finds the remaining miles
return milesGoal-currentMile;
}
public void halfMile(){ // Divides the desired goal halfway (Miles)
milesGoal = milesGoal/2;
}
public void setMileGoal(double newMile){ // Allows you to set a new goal
milesGoal = newMile;
}
public double getMileGoal(){
return milesGoal;
}
// KILOMETER METHODS
public double remainingKilos(){ // Finds the remaining Kilos
return kilosGoal-currentKilo;
}
public void halfKilo(){ // Divides the desire goal halfway (Kilos)
kilosGoal = kilosGoal/2;
}
public void setKiloGoal(){ // Allows you to set a new goal
kilosGoal = milesGoal*1.6;
}
public void setCurrentKilo(){ // Allows you to set the current Kilo
currentKilo = currentMile * 1.6;
}
// UNIQUE METHODS
public double getMilesStatus(){
return currentMile;
}
public double getKilosStatus(){
return currentKilo;
}
public String getHorseBreed(){
return horseBreed;
}
public void convertToKilos(){ // Converts current miles to kilometers
double kilos = currentMile * 1.6;
System.out.println("The current miles to kilometers is: " + kilos + "km.");
}
public void convertToMiles(){ // Converts current kilometers to miles
double miles = currentKilo * .6;
System.out.println("The current kilometers to miles is: " + miles + "m.");
}
public void milesPerHour(double hours){ // Calculates the mph to the goal by a time
double answer = milesGoal / hours;
System.out.println("The mph needed to reach the desination in " + hours + " hours: " + answer);
}
public void kilosPerHour(double hours){ // Calculates the kmph to the goal by a time
double answer = kilosGoal / hours;
System.out.println("The kilometers needed to reach the desination in " + hours + " hours: " + answer);
}
public int compareTo(Object Other){
if(milesGoal > (Horse)milesGoal.Other)
return 1;
if(milesGoal < (Horse)milesGoal.Other)
return 0;
return -1;
}
}
The Car class is pretty much the same as the Horse one and I need to find a way to compare both of their milesGoal to see which one is greater. I tried multiple things but it doesn't seem to work
This is the interface I made:
abstract interface milesInterface{
public double remainingMiles();
public void halfMile();
public void setMileGoal(double newMile);
public int compareTo(Object Other);
}
abstract interface kilometersInterface{
public double remainingKilos();
public void halfKilo();
public void setCurrentKilo();
public int compareTo(Object Other);
}
First, you are writting attribute.object. This is what fails. Other.milesGoal is a better option.
Another problema is with the casting. What you are doing is trying to cast milesGoal.other to Horse (you want to cast milesGoal)
You should use
if (milesGoal > ((Horse) other).milesGoal)
Also, use proper capitalization (variables go in lowercase, clases/interfaces in uppercase) and setters and getters.
Additionally, you probably will want to cast to the interface so you can use the methods with other clases that implement it
if (milesGoal > ((MilesInterface) other).milesGoal)
Firstly, (Horse)milesGoal.Other should be ((Horse) Other).milesGoal.
I would suggest overloading compareTo with one method for comparing to Horses and one method for comparing to Cars. Then your code looks like
public int compareTo(Horse horse){
if(milesGoal > horse.milesGoal)
return 1;
if(milesGoal < horse.milesGoal)
return -1;
return 0;
}
public int compareTo(Car car){
if(milesGoal > car.milesGoal)
return 1;
if(milesGoal < car.milesGoal)
return -1;
return 0;
}