Dice simulation, very newbie

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!"); } 

Sorry ... this might be a dumb question, but I'm very new to java
I have to create a dice game. The rule is simple, if the computer has more than the player, then the computer wins, and if the player has a larger number, the player wins. I have to create this using the If statement .. But I get a message stating that "a non-stationary variable cannot be specified from a static context", and also I got an error message "cannot find a character winner", I don’t know how to do it. Thank you so much for your help.

+5
source share
2 answers

There are a couple of problems here, the first player, the computer are non-static variables, and you want to access them in the static method (main) to make them static. The second is to declare a winner outside the diceRoll () method, so that you can use it mainly make, also by the way. Third. Make the winner a string, as you want to keep the name of the winner.

 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"; } } } 
+5
source
  • You cannot reference a non-static class variable in the main function.
  • The 'winner' variable, which is local to the diceroll function, cannot be accessed in the main.

Change the code above two points and it should work. 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; } } 
+2
source

Source: https://habr.com/ru/post/1272416/


All Articles