1

My program calculates the surface area of a cone (pi * radius * slant-height). I'm using an if-elseif ladder which says that if the slant-height is left empty and the vertical-height is entered, the program will calculate the slant-height via Pythagoras theorem. But I don't know how to make the program accept a null value

I tried using if(slant_height==null) but it says that the types are incompatible and == is a "bad operator type"

{
public void CSAcone(double radius,double slant_height,double height) {
    if (slant_height == null)
    {
         slant_height=Math.sqrt((radius*radius) + (height*height));
         double CSA=(22*radius*slant_height) / 7;

         System.out.println("radius= "+radius);
         System.out .println("height= "+slant_height);
         System.out .println("Curved Suface Area= "+CSA);
    }

    if(height == null) 
    {
        double CSA=(22*radius*slant_height) / 7;

        System.out.println("radius= " + radius);
        System.out.println("height= " + slant_height);
        System.out.println("Curved Suface Area= " + CSA);
    }
}}

Spangen
  • 4,420
  • 5
  • 37
  • 42

3 Answers3

1

try this :

 public void CSAcone(double radius, double slant_height, double height) {
    if (slant_height == 0.0f) {
        slant_height = Math.sqrt((radius * radius) + (height * height));
        double CSA = (22 * radius * slant_height) / 7;
        System.out.println("radius= " + radius);
        System.out.println("height= " + slant_height);
        System.out.println("Curved Suface Area= " + CSA);
    }
    if (height == 0.0f) {
        double CSA = (22 * radius * slant_height) / 7;
        System.out.println("radius= " + radius);
        System.out.println("height= " + slant_height);
        System.out.println("Curved Suface Area= " + CSA);
    }
}
mohammadReza Abiri
  • 1,759
  • 1
  • 9
  • 20
0

null can be cast to any reference type, but not to any primitive type such as int or boolean.

You can use primitive types and send a special value to specify emptyness.

Or just use object types (Integer, Boolean, Double etc.) and check null values(as you did).

public void CSAcone(Double radius,Double slant_height,Double height){
   if(radius == null){}
   if(slant_height == null){}
   if(height == null){}
   // ...
}
coder21
  • 1
  • 1
  • 4
0

Change your variable types to the wrapper classes(Integer, Double) of primitive types(int, double). In Java, primitive types cannot be null.

thuva4
  • 1,185
  • 8
  • 13