2017-10-07 77 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; 

    } 
}