hello. i have just started learning functions in java. i have done the below program to find area of rectangle,triangle and square. it is a private class.

class calcu
    {
        void rectangle(int l,int b)
        {
            int area1;
            area1=l*b;
            System.out.println("area of rectangle = "+area1);
        }
        void triangle(double base,double h)
        {
            double area2;
            area2=(0.5)*base*h;
            System.out.println("area of trinagle = ="+area2);
        }
        void square(int len)
        {
            int area3;
            area3=len*len;
            System.out.println("area of square = ="+area3);
        }
        public static void main(int m,int n,double o,double p,int q)
        {
            int a,d;
            double c;
            calcu obj=new calcu();
            a=obj.rectangle(m,n);
            c=obj.triangle(o,p);
            d=obj.square(q);
        }}

when i compile this program, i get an error that "incompatible types-found void but expected int".can anyone say what mistake i have done?

Recommended Answers

All 4 Replies

Your "square" method has void as its return type, but you're trying to read a returned value from it. Set the return type to "int" (since you're only acepting integer input parameters) and return the value of area3, and it should be fine.

Member Avatar for coil

You are trying to assign void to an integer/double here:

int a,d;
double c;
calcu obj=new calcu();
a=obj.rectangle(m,n);
c=obj.triangle(o,p);
d=obj.square(q);

Your methods (the Java terminology for a 'function') return void, but a, c, and d are integers/doubles - obviously, you can't assign "void" to an int/double.

Two quick fixes:
1. Change the methods to return ints/doubles
or
2. Get rid of all of the ints/doubles. I'm not sure what they even do. The methods print out to the console on their own. To call them, simply type obj.rectangle(m, n); .

Megha SR
Even you have corrected all the errors accordingly you are still unable to run this program.
If you run it, the following error will be printed:
Exception in thread "main" java.lang.NoSuchMethodError: main
You should define a proper main method which requests only one argument: a String array: String args[].
So if you insert the proper main method, for example, as follows, the JVM will interprete it and prints output.

public static void main(String args[]){
	main(2,3,4,5,6);
}

Having multiple methods with the same name is known as method overloading.
It looks strange, but the compile can figure it out because the args to each method are different.

The overloaded methods should have the same functionality. In your case they don't, so it be better if the method names were different.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.