我對編程很陌生,不太瞭解。我一直在試圖建立一個簡單的遊戲,用戶和計算機通過滾動骰子來爭奪積分。我的方法發佈如下。電腦只允許每回合獲得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");
}