0

Getting a not initialised error for my area calculation program. I need for it to stay as double not int so it will be able to accept decimal numbers. Here is the error. AreaCalculationProgram.java:39: error: variable width might not have been initialized areaofrectangle = width * length;

And here is my code:

     //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);

Thanks

Espon
  • 11
  • 3
  • 1
    What values you expect `width` and `length` to have when you execute `areaofrectangle = width * length;`? Why do you think these values would be there? – Pshemo Mar 18 '16 at 01:24

2 Answers2

1

You have to initialize them to 0 like below.

double areaofrectangle, width = 0, length = 0;

Class and instance variables have a default value of string being null, int being 0, boolean being false . we don't need to define them. But local variables like in your case width and length don't have a default value. Unless a local variable has been assigned a value , the compiler will always give an error

A lot of reasons are discussed at the below link Why must local variables, including primitives, always be initialized in Java?


Try the below code. it works. u can modify the code as per your requirements

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);
Community
  • 1
  • 1
LearningPhase
  • 1,277
  • 1
  • 11
  • 20
  • I know that, but the values have to inputed when run. so I can define them as 0. @LearningPhase – Espon Mar 18 '16 at 01:31
  • I tried that, but when you enter it as zero you cant input values for width and length when you run it. @LearningPhase – Espon Mar 18 '16 at 01:36
1

Compiler will give compile time error for local variables if any local variable is used without initializing it. From your code snippet it is clear then you are not initializing the variables width and height.

Pushpendra Pal
  • 640
  • 6
  • 19