getting error while compiling java program

Tags:



i’m getting this error while compiling the java program to find the area of square & rectangle using overload constructor .

square.java:18: error: <identifier> expected
public Static void main(String args[])throws IOException;
             ^
1 error

this is my code

import java.io.*;
class area
{
    int a,l,b;
    area(int a1)
    {
        a=a1;
        System.out.println("area of square is " + a*a);
    }
    area(int l,int b)
    {
        l=l1 ;
        b=b1 ;
        System.out.println("area of rectangle is " + l1*b1);
    }
    class square
    {
        public Static void main(String args[])throws IOException;
        {
            int a2,b2,l2,ch;
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            while(true)
            {
                System.out.println("enter your choice 1.square 2.rectangle 3.exit");
                ch=Integer.parseInt(br.readLine());
                switch(ch)
                {
                    case 1:
                        System.out.println("enter the side of square ");
                        a2=Integer.parseInt(br.readLine());
                        area ar=new area(a2);
                        break;
                    case 2:
                        System.out.println("enter sides of rectangle ");
                        l2=Integer.parseInt(br.readLine());
                        b2=Integer.parseInt(br.readLine());
                        area ar2=new area(l2,b2);
                        break;
                    case 2:
                        System.exit(0);
                        break;
                }
            }
        }
    }
}

Answer

You have multiple errors in your file:

area(int l,int b)
{
  l=l1 ;
  b=b1 ;
  System.out.println("area of rectangle is " + l1*b1);
}

There is no variable l1 and b1. You want to rename your method parameters.

public Static void main(String args[]) throws IOException;

Static is not a valid keyword. You want to use static. And you don’t want the semicolon at the end of the line.

But also – static is not allowed here. You either need to declare your square class in a separate file or you need to make it static

static class square {
  public static void main(String args[]) throws IOException {
  ...
  }
}

Also finally your label “2” in the switch case is duplicated.

case 2:
  System.out.println("enter sides of rectangle ");
  l2 = Integer.parseInt(br.readLine());
  b2 = Integer.parseInt(br.readLine());
  area ar2 = new area(l2, b2);
  break;
case 2:
  System.exit(0);
  break;

I found all that just by copying your code into an IDE.

Further I would suggest:

  • Class names should start with an uppercase Letter. So use Area instead of area and Shape instead of shape.
  • Move every class to a separate file, so you have a Area.java and Shape.java
  • Format your code for readability


Source: stackoverflow