0

I am new to object and classes. I am creating this test program to get the area of the triangle. I kept getting 0 as the area. I have no idea where did I get it wrong.

public class Project1 {
    public static void main(String args[]) {
        Triangle triangle1 = new Triangle();

        System.out.println("The area of the triangle with base "
            + triangle1.base + "and with width "
            + triangle1.width + " is " + triangle1.getArea());
    }
}

class Triangle {
    double base = 1.0;
    double width = 1.0;

    double getArea() {
        return  1 / 2 * base * width;
    }
}
Zabuzard
  • 25,064
  • 8
  • 58
  • 82

4 Answers4

1

Change the following

 double getArea() {
        return  1/2 * base * width;
    }

To

 double getArea() {
        return  0.5 * base * width;
    }

Due to integer division 1/2 yields 0.

Md Johirul Islam
  • 5,042
  • 4
  • 23
  • 56
1

try to use double numbers at getArea() method something like this:

double getArea() {
    return  1.0 / 2.0 * base * width;
}
mohsenJsh
  • 2,048
  • 3
  • 25
  • 49
0

Explanation

You are computing 1 / 2.

This is integer division which does not support decimal values. It always rounds towards zero, the result is thus

1 / 2 = 0

Because of that the computation gets 0 too.


Solution

You can fix it by dividing decimal values instead of integers:

return  1.0 / 2.0 * base * width;

There is no integer division as soon as one of the operands is a decimal value like a double or float. You indicate double by adding the dot like 2.0.

Alternatively you could use the decimal value 0.5 right from the start:

return 0.5 * base * width;

Note that both versions are equally fast since the compiler will pre-compute such constant computations at compile-time. The bytecode will thus have 0.5 for both versions.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
0

It is very common mistake for Java beginners, and I admit I sometimes still make this mistake. When divide one integer by another integer in Java, the result will be an integer as well. So while you expect 1 / 2 will be 0.5, the result will be 0 (i.e. it is truncated). You could cast the number first to force the division to use float or double like:

1 / (float) 2
1 / (double) 2

Or use the shorthand:

1 / 2f
1 / 2d

where f cast the number before it to float, and d to double.

Antony Ng
  • 767
  • 8
  • 16