java - 编译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;
}
}
}
}
}
解决方案
您的文件中有多个错误:
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
代替area
和Shape
代替shape
。 - 将每个类移动到一个单独的文件中,这样您就有了 Area.java 和 Shape.java
- 格式化代码以提高可读性
推荐阅读
- dropzone.js - 将 maxfiles 动态添加到 dropzone
- java - 运行 @DataJpaTest Junit 时,正在使用资源和测试资源文件夹中的两个 data.sql 文件
- image - React Native 从数据库中检索图像文件路径
- java - 为什么我的 Java Boggle 代码不起作用?
- php - HTTP 标头“内容类型:多部分/混合”导致“400 错误请求”
- javascript - PHP脚本中的echo内的JavaScript函数没有调用
- c# - 如何修复错误:无法将 int 隐式转换为字符串
- javascript - 在 React 子父组件中将 Props 向上传递到多级
- ruby-on-rails - 从 Ruby 中的字符串动态设置对象属性的更优雅的方法
- c++ - C++ 我应该使用什么来保存格式化为 sprintf() 之类的字符串变量?