变量未在Java中初始化 - 错误39

时间:2016-03-18 01:21:25

标签: java compiler-errors initialization

为我的区域计算程序获取未初始化的错误。我需要它保持双倍而不是int,所以它将能够接受十进制数。 这是错误。 AreaCalculationProgram.java:39:错误:可能没有初始化变量宽度          areaofrectangle = width * length;

这是我的代码:

     //Code for Rectangle

     double areaofrectangle, width, length;
     //int areaofrectangle;
     System.out.print(" -->  Enter Width of Rectangle in Centimetres: ");
     //Scanner sc = new Scanner(System.in);        //Scanner is for testing rectangle by its self
     //int width = sc.nextInt();
     // double width = sc.nextDouble();
     System.out.print(" -->  Enter Length of Rectangle in Centimetres: ");
     //int length = sc.nextInt();
     // double length = sc.nextDouble();
     areaofrectangle = width * length;
     System.out.print("Area of Rectangle: "+ areaofrectangle);

由于

2 个答案:

答案 0 :(得分:1)

你必须将它们初始化为0,如下所示。

double areaofrectangle, width = 0, length = 0;

类和实例变量的默认值为string为null,int为0,boolean为false。我们不需要定义它们。但是像你的情况宽度和长度这样的局部变量没有默认值。除非为局部变量分配了值,否则编译器将始终给出错误

以下链接讨论了很多原因 Why must local variables, including primitives, always be initialized in Java?

尝试以下代码。有用。你可以根据你的要求修改代码

double areaofrectangle = 0;

         System.out.print(" -->  Enter Width of Rectangle in Centimetres: ");
         Scanner sc = new Scanner(System.in);        //Scanner is for testing rectangle by its self
         double width = 0;
         width  = sc.nextDouble();
         System.out.print(" -->  Enter Length of Rectangle in Centimetres: ");
         double length = 0;
         length  = sc.nextDouble();
         areaofrectangle = width * length;
         System.out.print("Area of Rectangle: "+ areaofrectangle);

答案 1 :(得分:1)

如果使用任何局部变量而未初始化,编译器将为局部变量提供编译时错误。从您的代码片段中可以清楚地看到,您没有初始化变量width和height。