Java代码出现非法修饰符与语法错误(涉及VariablesDeclarators)
Java代码语法错误修复(涉及VariablesDeclarators)
问题说明
这段Java代码存在非法修饰符与语法错误,涉及VariablesDeclarators。最初尝试将public替换为double时,工具提示需将public static void替换为public static double;在第14、22行添加括号及参数后,又出现错误提示:Syntax error on token "public", record expected after this token、Syntax error, insert "RecordBody" to complete RecordDeclaration(第14行重复出现)。
错误代码
import java.util.Scanner; public class Rectangle { private static double setLength1 = 0; private static double setWidth1 = 0; public static void main(String[] args){ // TODO Auto-generated method stub { Scanner scan = new Scanner(System.in); System.out.println(" Today we`ll find the dimensions of a rectangle."); } public setLength1(double setLength1); { double setlength1; System.out.println("What is the length: "); Scanner scan; setLength1 = scan.nextDouble(); return setLength1; } public setWidth1(double setWidth1); { double setWidth1; System.out.println("What is the Width: "); Scanner scan; setWidth1 = scan.nextDouble(); return setWidth1; } double getArea; { return setWidth1 * setLength1; } double getPerimeter; { return 2*(setWidth1+setLength1); } } }
错误原因拆解
- 方法嵌套定义:Java不允许在
main方法内部定义其他方法,所有方法必须直接放在类的作用域下。 - 方法声明语法错误:方法声明必须明确返回值类型,比如
public static double setLength1(double length),原代码缺少返回值类型,还错误地加了分号。 - 变量未初始化/重复声明:内部重新声明
Scanner scan但未初始化,直接调用scan.nextDouble()会导致空指针;成员变量与方法参数重名,且局部变量重复声明。 - 方法定义格式错误:
getArea、getPerimeter的写法不符合方法规范,正确格式应为返回值类型 方法名(){}。
修复后的代码
import java.util.Scanner; public class Rectangle { private static double length = 0; private static double width = 0; public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Today we'll find the dimensions of a rectangle."); // 获取长和宽 setLength(scan); setWidth(scan); // 计算并输出结果 System.out.println("Area of the rectangle: " + getArea()); System.out.println("Perimeter of the rectangle: " + getPerimeter()); scan.close(); } // 设置长度的方法 public static void setLength(Scanner scan) { System.out.println("What is the length: "); length = scan.nextDouble(); } // 设置宽度的方法 public static void setWidth(Scanner scan) { System.out.println("What is the Width: "); width = scan.nextDouble(); } // 计算面积的方法 public static double getArea() { return width * length; } // 计算周长的方法 public static double getPerimeter() { return 2 * (width + length); } }
内容的提问来源于stack exchange,提问作者E.schneider
相关产品推荐
相关产品推荐

