2012-11-30 39 views
1

我剛剛接觸到Java語言,所以我通常會遇到平庸錯誤。以下應該是其中之一。 Es1.java:93:錯誤:變量f可能未被初始化 查看代碼之前要知道的事情 - 我正在使用一些自定義類:ConsoleInputManager和ConsoleOutputManager基本上像Scanner和System.out一樣工作;圖是一個抽象類;圓形,方形和矩形圖擴展變量可能未被初始化(抽象類)

import prog.io.*; 
//ConsoleInputManager, ConsoleOutputManager 
import prog.utili.*; 
//Figure, Circle, Squade, Rectangle 
class Es1{ 
public static void main(String[] args){ 

//Variables 
ConsoleInputManager in = new ConsoleInputManager(); 
ConsoleOutputManager out = new ConsoleOutputManager(); 
int com1,com2,com3; 
com1 = com2 = com3 = 0; 
double r,s,l,w; 
r = s = l = w = 0.0; 
Figure f; 

do{ 
    //Menu 
    out.println("1. Insert a new figure"); 
    out.println("2. Calculate the area of the current figure"); 
    out.println("3. Examine the current figure"); 
    out.println("4. Exit the program\n"); 

    //Input 
    com1 = in.readInt("Command: "); 

    //New figure 
    if (com1 == 1){ 
     do{ 
      out.println("1. Circle"); 
      out.println("2. Square"); 
      out.println("3. Rectangle"); 
      out.println("4. Back to main menu\n"); 
      com2 = in.readInt("Command: "); 
      //Circle 
      if (com2 == 1){ 
       s = l = w = 0.0; 
       do{ 
        r = in.readDouble("Radius: "); 
       } while (r <= 0); 
      } 
      else 
      //Square 
      if (com2 == 2){ 
       r = l = w = 0.0; 
       do{ 
        s = in.readDouble("Side: "); 
       } while (s <= 0); 
      } 
      else 
      //Rectangle 
      if (com2 == 3){ 
       r = s = 0.0; 
       do{ 
        l = in.readDouble("Length: "); 
       } while (l <= 0); 
       do{ 
        w = in.readDouble("Width: "); 
       } while (w <= 0); 
      } 
     } while (com2 != 4); 
    } 
    else 

    //Area 
    if (com1 == 2){ 
     if (r != 0.0){ 
      f = new Circle(r); 
      out.println("Area = " + f.getArea()); 
     } 
     else 
     if (l != 0.0){ 
      f = new Square(s); 
      out.println("Area = " + f.getArea()); 
     } 
     else 
     if (b != 0.0){ 
      f = new Rectangle(l,w); 
      out.println("Area = " + f.getArea()); 
     } 
     else 
      out.println("It hasn't been inserted any figure"); 
    } 
    else 

    //Examination 
    if (com1 == 3){ 
     do{ 
      out.println("1. Examine the current figure"); 
      out.println("2. Back to main menu"); 
      com3 = in.readInt("Command: "); 
      if (com3 == 1){ 
       if (f instanceof Circle) 
        out.println("Circle"); 
       else 
       if (f instanceof Square) 
        out.println("Square"); 
       else 
       if (f instanceof Rectangle) 
        out.println("Rectangle"); 
       else 
        out.println("It hasn't been inserted any figure"); 
      } 
     } while (com3 != 2); 
    } 

} while (com1 != 4); 
} 
} 

回答

3
Figure f; 

上面的語句裏面main方法。如果/ else條件不滿足,有可能導致未分配。

它更改爲類似如下:

Figure f=null; 

所有的局部變量必須在使用前分配一定的價值。

除此之外,請確保在對f執行任何操作之前執行空檢查。

+0

謝謝,這是非常微不足道的,因爲我認爲! – Marco

0

Figure f;

這是未初始化。