I’ve just started programming in Java and I’ve encountered a problem that I just can’t seem to figure out.
My program is meant to roll a die with (n) sides, where (n) is specified by the user. The program will then print the result of the roll as an integer, the face value of the roll as an integer (this seems to be the same as the result of the roll), and the result of the roll as a string. The last two methods (face value and string) are separate methods from the die roll, but are still required.
My problem is that although the code compiles, the methods getFaceValue() and toString() return both return zero. My code is:
import java.io.*;
import java.util.*;
public class Die {
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() {
Scanner keyboard = new Scanner(System.in);
int sides = keyboard.nextInt();
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) {
System.out.println("How many sides will the die have?");
System.out.println(" ");
System.out.println("Roll: " + new Die().roll());
System.out.println("Face: " + new Die().getFaceValue());
System.out.println("String: " + new Die().toString());
}
}
I would greatly appreciate any help you can offer.
The first problem I see is that fact that you’re creating three instance of your Die class, meaning that any values genereted will not effect the others….
Should read
I’d also move the prompt
System.out.println("How many sides will the die have?")to therollmethod, seen as that’s where you’re actually asking the question, but that’s just me