I’m new to java and I’ve encountered yet another error with my dice program.
In this program I have three methods, roll() to roll the die and return a value between 1 and a number specified by the user, getFaceValue(), to return the value of the die roll as an int, and toString(), to return the die roll as a string.
The answer to my previous question about my program enabled me to get the program working, but it was not structured as the professor wanted, so I’ve had to rework it. I now know that none of my methods/variables can be static, and I can only take user input in the main part of the program.
When I try to compile, I get the following error:
Die.java:12: error: cannot find symbol
double y = (x * sides) + 1;
symbol: variable sides
location: class Die
My code is as follows:
import java.io.*;
import java.util.*;
public class Die {
//private int sides;
private int z;
private String faceName;
//sets (and returns) the face value to a uniform random number between 1 and the number of faces.
public int roll() {
double x = Math.random();
double y = (x * sides) + 1;
z = (int)y;
return z;
}
//returns the current face value of the die.
public int getFaceValue() {
int face = z;
return face;
}
//returns the string representation of the face value.
public String toString() {
faceName = Integer.toString(z);
return faceName;
}
public static void main(String [] args) {
int sides;
System.out.println("How many sides will the die have?");
Scanner keyboard = new Scanner(System.in);
sides = keyboard.nextInt();
System.out.println(" ");
Die die = new Die();
System.out.println("Roll: " + die.roll());
System.out.println("Face: " + die.getFaceValue());
System.out.println("String: " + die.toString());
}
}
Originally, I had the variable sides as a private int (you can see it commented out in my program), but this produced a static reference error.
I appreciate any help you can offer.
The previous question was: Methods in Dice Program return 0
You can create an instance variable for
sidesand pass it to the die via a constructor. This would require you to uncomment yourprivate int sidesvariable.Example Die constructor:
With a constructor like this, you can instantiate your Die with the number of sides you read as input.
Now, your die’s
sidesfield is set to whatever the user entered, and the die’s methods use that value accordingly.