2017-10-07 48 views
5
public class Dice 
{ 
    int player; 
    int computer; 

    public static void main (String[]args) 
    { 

     player = 1 + (int)((Math.random()*7)); 
     computer = 1 + (int)((Math.random()*7)); 
     diceRoll(); 
     System.out.println("You rolled a " + player); 
     System.out.println("Computer rolled a " + computer); 
     System.out.println("And the winner is" + winner); 

    } 

    public static void diceRoll() 
    { 
     boolean winner = player > computer; 

     if (winner) 
      System.out.println("You won!"); 

     if (!winner) 
      System.out.println("You lost!"); 



    } 

對不起......這可能是愚蠢的問題,但我很初學者的java
我應該創建一個骰子游戲。規則很簡單,如果計算機的數量大於玩家的數量,則計算機獲勝,如果玩家數量較多,則玩家獲勝。我必須通過使用If語句創建此.. 但我得到的錯誤說「非靜態變量不能從靜態上下文中引用」,並且我得到錯誤說「找不到符號獲勝者」 我不' t知道如何做到這一點.. 非常感謝你的幫助..模擬一個骰子游戲,非常初學者

+0

因爲你是內**主要使用類的全局變量(**播放**和** **電腦)()**和** diceRoll()**方法,其是**靜**,那些類全局變量也需要是靜態的。聲明你的變量:'static int player;'和'static int computer;' – DevilsHnd

回答

5

這裏有幾個問題,第一個玩家,計算機是非靜態變量,你想在靜態方法(主)中訪問它們,所以讓他們靜態。 第二次聲明diceRoll()方法之外的獲勝者,以便您可以在主要使用它的情況下也使用它。 第三名讓贏家成爲一個字符串,因爲你想保持贏家的名字。

public class Dice { 
    static int player; 
    static int computer; 
    static String winner; 

    public static void main(String[] args) { 

     player = 1 + (int) ((Math.random() * 7)); 
     computer = 1 + (int) ((Math.random() * 7)); 
     diceRoll(); 
     System.out.println("You rolled a " + player); 
     System.out.println("Computer rolled a " + computer); 
     System.out.println("And the winner is" + winner); 

    } 

    public static void diceRoll() { 

     if(player > computer){ 
      System.out.println("You won!"); 
      winner = "Player"; 
     }else{ 
      System.out.println("You lost!"); 
      winner = "Computer"; 
     } 
    } 
} 
2
  1. 你不能指在主函數類的不是靜態變量。
  2. '贏家'變量是本地的diceroll函數,不能在main中訪問。

修改上述兩點的代碼,它應該工作。 public class Dice static int player; static int computer;

public static void main (String[]args) 
    { 


     player = 1 + (int)((Math.random()*7)); 
     computer = 1 + (int)((Math.random()*7)); 
     boolean winner= diceRoll(); 
     System.out.println("You rolled a " + player); 
     System.out.println("Computer rolled a " + computer); 
     System.out.println("And the winner is" + winner); 

    } 

    public static boolean diceRoll() 
    { 
     boolean winner = player > computer; 

     if (winner) 
      System.out.println("You won!"); 

     if (!winner) 
      System.out.println("You lost!"); 

    return winner; 

    } 
}