Search code examples
javasystem.out

Error in System.out.println


Is there any error in the following code? It shows cant find symbol, symbol: class out location: class System. In the log, it show a lot of errors, including

java.lang.ClassFormatError: Method "" in class Area has illegal signature "(Ljava/lang/Object;)Ljava/lang/System$out$println;"

import java.util.*;
class Area
{
double pi=3.14;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of r");
int r=sc.nextInt();
System.out.println("enter the value h");
int h=sc.nextInt();
void areaOfCircle()
   {
     double area1=pi*r*r;
     System.out.println("area of circle="+area1);
   }
void areaOfCylinder()
   {
     double area2=2*pi*r*(r+h);
     System.out.println("area of cylinder="+area2);
   }
public static void main(String args[])
   {
     Area a=new Area();
     a.areaOfCircle();
     a.areaOfCylinder();
   }
}

Solution

  • The statement System.out.println(""); should be written in some block. It cannot be written directly in class.

    public class ClassName {
       System.out.println("this statement gives error"); // Error!! 
    }
    

    Either it should be inside curly braces {...} like:

    { System.out.println("this works fine"); }
    

    This way is an initializer block.

    Or it should be written in a method like:

    public void methodName(){
        System.out.println("inside a method, prints fine");
    }
    

    Your complete program should be like:

    public class Area {
    double pi = 3.14;
    int r;
    int h;
    
    void areaOfCircle() {
        double area1 = pi * r * r;
        System.out.println("area of circle=" + area1);
    }
    
    void areaOfCylinder() {
        double area2 = 2 * pi * r * (r + h);
        System.out.println("area of cylinder=" + area2);
    }
    
    public static void main(String args[]) {
    
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the value of r");
        Area a = new Area();
        a.r = sc.nextInt();
        System.out.println("enter the value h");
        a.h = sc.nextInt();
        a.areaOfCircle();
        a.areaOfCylinder();
       }
    }