2011-01-20 106 views
0

我在學習構造函數。
當我嘗試編譯下面的代碼時,出現錯誤「變量輸入和形狀未初始化」。可變內部的Luse構造函數

有誰能告訴我爲什麼以及如何解決它?

public class Try { 

    public static void main(String[] args) 
    { 
     String input;//user key in the height and width 
     int shape;//triangle or square 

     Count gen = new Count(input , shape);//is this the right way to code? 
     gen.solve(); 
    } 
} 

public class Count { 

    public Count(String inp, int shp) { 

     String input_value = inp; 
     shape_type = shp; 
    } 

    public void solve() { 

     if shape_type==3{ 
      //count the triangle 
     } 
     else if shape_type==4{ 
      //count the square 
     } 
    } 
} 
+0

你必須初始化你的變量。 int形狀的情況下它並不重要它只是一個瘋狂的數字,但在輸入的情況下,它的一個對象,你必須初始化它,否則你程序會崩潰。你至少應該做input = null,但是由於它的一個字符串,你應該做input =「」;或者input = new String();或者放一些文字; – 2011-01-20 01:33:58

回答

1

你還沒shapeinput值尚未嘗試使用它們之前。或者你現在可以給他們虛擬值,比如

String input = "test"; 
int shape = 3; 

或者從用戶那裏獲取字符串和整數;在這種情況下,您可能需要查看如何使用Scanner

通過留下的輸入和形狀沒有價值,在:

String input; 
int shape; 

他們初始化,所以Java不知道他們的價值到底是什麼。

1

我認爲這是某種功課。我冒昧地修改了代碼並修改了一下代碼。

您必須初始化您要使用的任何變量。唯一的例外是當你使用類成員時(那些會自動初始化爲某個默認值)。請參閱下文,Count類的成員未明確初始化。

這是一些工作代碼。另外請注意,我稍微改變了求解方法(if塊應該有()這個表達式,但是你想要做的通常更好的做法是使用switch塊,如下所示:我還在Count類中聲明瞭兩個成員要記住,以便在施工時提供的值調用solve()方法時能夠使用它們。

public class Try { 

    public static void main(String[] args) { 
     String input = null; //user key in the height and width 
     int shape = 0; //triangle or square 

     Count gen = new Count(input, shape);//is this the right way to code? 
     gen.solve(); 
    } 

} 

class Count { 

    String input_value; 
    int shape_type; 

    public Count(String inp, int shp) { 
     this.input_value = inp; 
     this.shape_type = shp; 
    } 

    public void solve() { 
     switch (this.shape_type) { 
      case 3: 
       // count the triangle 
       break; 
      case 4: 
       // count the square 
       break; 
     } 
    } 
} 

代碼的正確的格式通常有助於:)。