Reputation: 53
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 stupid question but I am very beginner to java
I am supposed to create a dice roll game. The rule is simple, if computer has larger number than the player, then the computer wins, and if player has larger number, then the player wins. I have to create this by using If statement..
But I am getting the error saying that "non static variable cannot be referenced from a static context" and also I got the error saying " cannot find the symbol winner"
I don't know how to do this..
Thank you so much for your help..
Upvotes: 5
Views: 778
Reputation: 374
Modify the code for 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;
}
}
Upvotes: 2
Reputation: 3643
There are couple of problems here, first player, computer are non static variables and you want to access them in a static method (main) so make them static. Second declare winner outside of diceRoll() method so that you can use it in main make that static too. Third Make the winner a String as you want to hold the winner name.
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";
}
}
}
Upvotes: 4