Why is my constructor not working? - java

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;
}

Related

Trouble with Method undefined for a type Java

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;
}
}

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 Curiosity: Using a Float or Double for Costs in a Class

I was just working on a quick class for an item to be sold. Here is the code for said class:
public class Item{
private int itemNumber;
private double itemCost;
private String manName;
public Item(int inum, double icost, String mname){
itemNumber = inum;
itemCost = icost;
manName = mname;
}
public int getNum(){
return itemNumber;
}
public double getCost(){
return itemCost;
}
public String getName(){
return manName;
}
public void setNum(int inum){
itemNumber = inum;
}
public void setCost(double icost){
itemCost = icost;
}
public void setName(String mname){
manName = mname;
}
}
And here is the calling method in the simple driver app I was using to test:
public static void testItem(){
Item item = new Item(4,44.50,"Example1");
item.setCost(50.00);
item.setNum(3);
item.setName("Example2");
System.out.println(item.getNum() + " " + item.getCost() + " " + item.getName());
}
}
My curiosity is that, originally, I had used floats for the cost variables. However, when compiling, I got an error for possible data loss as it was casting from double TO float.
I had declared the variables as floats, but they were considered doubles, it would seem.
I'm only a very junior Java man, and am currently using TextPad as my editor. I'm just curious about this fact so that I can keep the answer in mind. Thanks, guys!
The compiler type errors are caused because 1.2 (eg.) is a double literal, while 1.2f is a float literal.
Changing all the types to double "fixed" this because there was no need to go convert from a double to a float. Other corrections would have been to use floating-literals (e.g. 50.0f) or to explicitly cast.
double d = 1.2; // GOOD, double
float f = 1.2; // BAD, double -> float ("error: possible loss of precision")
float f = 1.2f; // GOOD, float
float f = (float)1.2; // OK, double -> float by explicit cast
float f = 1; // OK, int -> float
Of course, neither double or float are "correct" for money, which should be dealt with using a fixed precision type, such as that provided by BigDecimal.
See also:
Why it the F postfix needed here to avoid an error?
Declaring floats, why default type double?
BigDecimal and Money

Calling an object from different classes

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.

Java:Arithmetic

Do you see anything wrong in this code? in thosen't work well it returns a NaN.
public class Method2 extends GUIct1
{
double x=0,y=0;
void settype1 (double conv1)
{
x = conv1;
}
void settype2 (double conv2)
{
y = conv2;
}
double conversion ( double amount)
{
double converted = (amount*y)/x;
return converted;
}
}
Way it is used an i already changed the set part
Method2 convert = new Method2(); \\ method is called
.....
convert.settype1(j);
.....
convert.settype2(k);
.....
double x = convert.conversion(i);
System.out.println(x);
Well, the fact that you've got methods which set variables called get-something is pretty obviously not a good idea, and there's no indentation... but it should work. But then, you haven't shown how you're using it. Perhaps you're not actually called the setter methods?
Here's an example of the same code but with different names, and a sample of using it:
class Converter
{
double multiplier = 0;
double divisor = 0;
void setMultiplier(double multiplier)
{
this.multiplier = multiplier;
}
void setDivisor(double divisor)
{
this.divisor = divisor;
}
double convert(double amount)
{
return (amount * multiplier) / divisor;
}
}
public class Test
{
public static void main(String[] args)
{
Converter converter = new Converter();
converter.setMultiplier(3.5);
converter.setDivisor(8.5);
System.out.println(converter.convert(2)); // Prints 0.8235294117647058
}
}
Personally I'd probably make the variables final and set them in the constructor, but that's another matter...
It doesn't look like you ever call gettype1 or gettype2 so the x/y is 0/0 resulting in NaN
This can happen when x=0. Division by zero is not defined. Print out x and y before you start to calculate to see whetther they are not zero.

Categories

Resources