java - Generate random number between 0000 and 9999 -
i need generate 4 digit number 0000 9999 , can't seem so. have code, generate 762 sometime, , can't allow that. need utilize these methods though 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); }
you need format random value using expression
string.format("%04d", randomvalue);
if randomvalue
762, phone call string.format
returns "0762", desired.
edit: in response comment below
please leave randomvalue
integer. want utilize code user interaction i.e. formatting. print randomvalue
use
system.out.printf("%04d\n", randomvalue);
and should utilize string.format
if there part of programme needs maintain string user interaction, there no need alter way store randomvalue
.
to compare user types in randomvalue
, can utilize integer.parseint. can use
int testvalue; seek { testvalue = integer.parseint(inputline, 10); } grab (numberformatexception ex) { // user typed in isn't number. alert user somehow, , create // him or seek 1 time again }
to typed-in value int, , compare testvalue
, randomvalue
==.
java
No comments:
Post a Comment