首页 > 解决方案 > 编译java程序时出错

问题描述

我在编译 java 程序以使用重载构造函数查找正方形和矩形的区域时遇到此错误。

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

这是我的代码

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;
                }
            }
        }
    }
}

标签: java

解决方案


您的文件中有多个错误:

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

没有变量 l1 和 b1。您想重命名方法参数。

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

静态不是有效的关键字。你想使用静态。而且您不希望在行尾使用分号。

而且 - 这里不允许使用静态。您要么需要在单独的文件中声明您的 square 类,要么需要将其设为静态

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

最后,您在开关盒中的标签“2”也被复制了。

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;

我只是通过将您的代码复制到 IDE 中找到了所有这些。

此外,我建议:

  • 类名应以大写字母开头。所以使用Area代替areaShape代替shape
  • 将每个类移动到一个单独的文件中,这样您就有了 Area.java 和 Shape.java
  • 格式化代码以提高可读性

推荐阅读