2016-06-13 74 views
1

我對Java很新,所以我不明白爲什麼我會收到初始化錯誤。在代碼中,我的整數「Memes」表示它可能沒有被初始化,並且局部變量隱藏在字段中。變量未初始化並隱藏在字段中

private void totalUpdate(int yes){ 


    if (yes==1){ 
      int CompBot = Integer.parseInt(lblbotComp.getText()); 
    int CompTop = Integer.parseInt(lbltopComp.getText()); 
    int CompMid = Integer.parseInt(lblmidComp.getText()); 

       int Memes = Memes + CompBot + CompTop + CompMid; 
      lbltotalComp.setText("Computer has earned "+ Memes +" points in total"); 
} 
    } 
private void pointUpdate(int points){ 
    pointsUser = pointsUser + points ; 
    lbluserPointsEst.setText (""+pointsUser+""); 
} 

private void computerPointUpdate(int pointComp){ 
    pointsComputer = pointsComputer + pointComp ; 
    lblcompPointsEst.setText (""+pointsComputer+""); 
} 

private int play(int points){ 
int score; 
int randomScore = (int)((100 -1 +1)*Math.random() +1); 
if (randomScore < points){ 
    score = points; 
    } 
    else{ 
    score = 100; 
    } 

return score; 
} 

private int playComp(int pointsComp){ 
int score; 
int randomScore = (int)((100 -1 +1)*Math.random() +1); 
if (randomScore < pointsComp){ 
    score = pointsComp; 
    } 
    else{ 
    score = 100; 
    } 

    return score; 
} 

     private int Memes = 0; 
     private final Timer messageTimer; 
     private int pointsComputer = 0; 
     private int pointsUser = 0; 
     private int count; 

回答

1

,因爲你在你的類定義有private int Memes您會收到這樣的警告,以及在totalUpdate()聲明的變量int Memes

如何解決這取決於你想要什麼:

如果你想totalUpdate()在你的對象更新的Memes價值,離開了int在線路中的問題是這樣的:

Memes = Memes + CompBot + CompTop + CompMid;

如果你想聲明一個新的局部變量,最好給它一個不同的名稱:

int localMemes = Memes + CompBot + CompTop + CompMid;

1

當你做到這一點

int Memes = Memes + CompBot + CompTop + CompMid; 

的Java將此視爲一個新的變量聲明,隱藏場

private int Memes = 0; 

它看起來像你想初始化Memes這是場。爲了做到這一點,滴int在分配的前:

Memes = Memes + CompBot + CompTop + CompMid; 
0

大概在這一行:

int Memes = Memes + CompBot + CompTop + CompMid; 

變量「模因」可以是在所述方法中totalUpdate定義的()或對象的屬性。所以解析器會感到困惑。

嘗試將變量的名稱更改爲像localMemes或類似的東西。

而且因爲你在Java中是新的,我建議閱讀命名約定這篇文章:http://www.oracle.com/technetwork/java/codeconventions-135099.html

0

申報 「模因」 在外地:

int Memes = 0; //for example 

然後

Memes += CompBot + CompTop + CompMid; 

整數/對象的小寫名稱也有助於類名稱的可讀性。

memes += compBot + compTop + compMid;