Castellanos
Castellanos

Reputation: 157

Generate random number between 0000 and 9999

I need to generate a 4 digit number from 0000 to 9999 and I can't seem to do so. I have this code, but it will generate 762 sometime, and I can't let it do that. I do need to use these methods though to generate it.

private java.util.Random rndGenerator = new java.util.Random();
private int randomValue;
public final static int NUMBER_OF_VALUES = 9999;


public GuessRandomValue() {
    randomValue = rndGenerator.nextInt(NUMBER_OF_VALUES);
}


public void setAnswer() {
    randomValue = rndGenerator.nextInt(NUMBER_OF_VALUES);
}  

Upvotes: 0

Views: 5724

Answers (1)

Adam Mihalcin
Adam Mihalcin

Reputation: 14478

You just need to format your random value using the expression

String.format("%04d", randomValue);

If randomValue is 762, the call to String.format returns "0762", as desired.


EDIT: In response to comment below

Please leave randomValue as an integer. You only want to use this code for user interaction i.e. formatting. So to print randomValue you would use

System.out.printf("%04d\n", randomValue);

and you should use String.format if there is any part of the program that needs to keep a string for user interaction, but there is no need to change the way you store randomValue.

To compare what the user types in to randomValue, you can use Integer.parseInt. So you can use

int testValue;
try {
    testValue = Integer.parseInt(inputLine, 10);
} catch (NumberFormatException ex) {
    // The user typed in something that isn't a number.  Alert the user somehow, and make
    // him or her try again
}

to get the typed-in value as an int, and just compare testValue and randomValue with ==.

Upvotes: 5

Related Questions