I generate a random number between 0-99 using this :
int num2= (int)(Math.random() * ((99) + 1));
When the number is below 10 I want it to print with a 0num2 So if the number is 9 it would be 09.
How can I get it to print this?
I generate a random number between 0-99 using this :
int num2= (int)(Math.random() * ((99) + 1));
When the number is below 10 I want it to print with a 0num2 So if the number is 9 it would be 09.
How can I get it to print this?
String str;
if (num2 < 10) str = "0" + num2;
else str = "" + num2;
System.out.println("Value is: " + str);
Have a look at PrintStream.format
, which will allow you to print using specified widths and padding characters.
System.out
is a PrintStream
, so you can use System.out.format
in place of println
.
Your case is pretty simple, look over the syntax for the format string:
System.out.format("%02d", num2);
Here 2 is the minimum width, and the 0 specifies that the result be padded with zeros, if the width of the result is less than 2.
You can use the approach of removing an extra digit instead.
System.out.println(("" + (int)(Math.random()*100 + 100)).substring(1));
or to use the String format.
String s = String.format("%02d", (int)(Math.random()*100));
or
System.out.printf("%02d", (int)(Math.random()*100));
I would generally use the last option as it allows you to combine other strings and print them.