Random generated number
How would you set up a program using Java to generate a 5 digit number using the following statement:
int n = (int)Math.floor(Math.random()*100000+1)
开发者_运维知识库It also has to print the number generated. I have tried writing this different ways and keep coming up with errors.
There are two ways of looking at your problem. Either you need to make sure the random number generator only produces numbers with exactly five digits (in the range 10000 - 99999) or you need to print the numbers with leading 0s when a number is produced that's too low.
The first approach is best met using Java's Random class.
Random rand = new Random();
int n = rand.nextInt(90000) + 10000;
System.out.println(n);
If you're restricted in some way that you must use the statement in your question, then the second approach is probably what you're after. You can use Java's DecimalFormat class to format a random number with leading zeros before printing.
n = (int)Math.floor( Math.random() * 100000 + 1 );
NumberFormat formatter = new DecimalFormat("00000");
String number = formatter.format(n);
System.out.println("Number with lading zeros: " + number);
One might do:
public class Test {
public static void main(String[] args) {
int n = (int)Math.floor(Math.random()*100000+1);
System.out.println(n);
}
}
However, this really isn't the preferred way of generating random integers. Check out the Random class.
Random r = new Random();
for (;;) {
System.out.println(10000 + r.nextInt(90000));
}
A better idea is to generate the number by successively generating 5 random digits. Making the first digit non-zero ensures that the generated number is always 5-digit. I'm posting pseudocode below, it should be easy to convert it into Java code.
A = List(1,2,3,4,5,6,7,8,9)
B = List(0,1,2,3,4,5,6,7,8,9)
output = 0
output=random.choice(A) //first digit from A, no zeros
for i=0 to 4
output=output*10
output=output+random.choice(B) //next digits from B, can have zero
return output
Look up the API docs for Random if you are stuck.
A way to get a random number 00000 - 99999 is to use the following.
Random r= new Random();
// possibly too obtuse for most readers. ;)
System.out.println((""+(100000+r.nextInt(100000))).substring(1));
精彩评论