I have a homework assignment where I am supposed to simulate the roll of a dice using math.random() and changing it to an int. I have a single file with 2 classes and am attempting to make an object. My code compiles with the run time error "error: non-static variable this cannot be referenced from a static context." Any Idea what is happening.
I have changed the value of "value" to an integer and successfully ran the code. No other changes have come to mind yet.
public class DieTester_5AlastiCorrigan {
public static void main(String[] args){
// New object myDie.
Die myDie = new Die();
System.out.println(myDie.roll());
System.out.println(myDie.getValue());
}
// Creates a new Die Class
class Die{
private String value;
public Die( int dieRoll ) {
value = "" + dieRoll;
}
// Roll Method chooses random number between 1 - 7 and makes it an int.
public int roll() {
int max = 6;
int min = 1;
int range = max + 1;
int dieRoll = (int)Math.random()*range;
//dieRoll = (int)dieRoll;
return dieRoll;
}
// getValue Method returns final value of "value".
public String getValue() {
return value;
}
}
}
Expect the console to print out a number 1 <= x < 7 as an integer.
Error message: error: non-static variable this cannot be referenced from a static context Die myDie = new Die(); ^
Notice how your Die
class is inside your DieTester_5AlastiCorrigan
class. That makes it an non-static inner class. You would need an instance of DieTester_5AlastiCorrigan
to create an instance of Die
. So to fix this, simply move Die
to the top level, like this:
class DieTester_5AlastiCorrigan {
...
}
class Die {
...
}
Or add a static
modifier:
class DieTester_5AlastiCorrigan {
...
static class Die {
...
}
}
However, there are still a few mistakes in your code. Die
has a constructor that takes an int
, but when you are creating a Die
, Die myDie = new Die();
, you are not passing an int
to the constructor. I suggest that you add a parameterless constructor:
public Die() {
this(1);
}
Also, value
should not be of type String
. It should be an int
, and judging from your usage, roll
should change the value of value
instead of returning the die roll.