2014-02-22 36 views
0

我對編程很陌生,不太瞭解。我一直在試圖建立一個簡單的遊戲,用戶和計算機通過滾動骰子來爭奪積分。我的方法發佈如下。電腦只允許每回合獲得20點。如何在類中使用方法內計算的變量值?

我的問題是,我需要在方法被調用和完成後記住變量computerTotal的值。我想確保每當computerTurn方法完成後,我可以在該方法之外使用計算的變量computerTotal。我試圖在.java文件類(但方法的外部)中建立一個新的int,然後在該方法內使用該int來保存該值,但是我收到有關整數需要靜態的錯誤?

這對我來說都非常困惑。誰能幫我嗎?

公共靜態無效computerTurn() {

System.out.println("Passed to Computer."); 

    Die computerDie1, computerDie2; 
    int computerRound, computerTotal; 
    computerRound = 0; 
    computerTotal = 0; 


    while (computerTotal < 21){ 
    computerDie1 = new Die(); 
    computerDie2 = new Die(); 
    computerDie1.roll(); 
    computerDie2.roll(); 

    System.out.println("\n" + "CPU Die One: " + computerDie1 + ", CPU Die Two: " + computerDie2 + "\n"); 
    computerRound = computerDie1.getFaceValue() + computerDie2.getFaceValue(); 

    int cpuDie1Value; 
    int cpuDie2Value; 

    cpuDie1Value = computerDie1.getFaceValue(); 
    cpuDie2Value = computerDie2.getFaceValue(); 

    System.out.println ("Points rolled this round for the Computer: " + computerRound); 

    computerTotal = computerTotal + computerRound; 

    System.out.println ("Total points for the Computer: " + computerTotal + "\n"); 
    } 

回答

0

任何一個方法中創建的變量是「局部變量」,意味着它們不能該方法之外使用。把一個靜態變量放在一個方法之外來創建可以在任何地方使用的「全局變量」。

0

的方法添加到您的類

public static int getComputerTotal() { return ComputerTotal;} 

然後你就可以獲取類之外的值通過執行類似:

ComputerTurn(); 
ComputerTurn.getComputerTotal(); 
0

把變量外的方法是正確的跟蹤,但由於此方法是static(意思是它不能訪問依賴於對象實例的變量),它只能訪問靜態變量。在類中聲明computerTotal的方法外,使用以下:

private static int computerTotal; 

你或許應該做一些研究,在面向對象編程和Java中的意思static

0

將computerTotal聲明爲您類的成員變量,以使其值甚至在函數外部可用。

class MyClass{ 
    private int computerTotal ; 

    public void function myFunction() 
    { 
     ........ 
     ......... // your calculations 
     computerTotal = computerTotal + computerRound;  

    } 

    public int getComputerTotal(){return  computerTotal ;} 

}

0

您必須聲明任何方法外computertotal來留住他們。所以像這樣:

public class name { 
    int computertotal = 0; //v=can just uuse int computertotal; 
    public void method() { 
     while(computertotal < 20) { 
       computertotal += 1; 
     } 
    } 
} 

現在他變量被保存!

0

您可能需要添加一些setters和getters來從另一個類中獲取int。

class NewClass { 
    private int yourInt = 1; 
} 

它告訴你使它成爲一個靜態變量,因爲你可以在一份聲明中像

NewClass.yourInt; 

來調用它,一個靜態變量是指與一個類關聯,而不是那個對象類。

安裝程序和獲取程序是允許您從其他類中檢索或設置私有值的方法。您可能想要將它們添加到聲明int的NewClass中。安裝者和獲得者看起來像這樣。

二傳手:

public void setYourInt(int newInt) { 
    this.yourInt = newInt; 
} 

消氣:

public int getYourInt() { 
    return this.yourInt; 
} 
相關問題