I cannot find the proper syntax for a string format as well as setting it up for a output that adds the leading zeros IF the value inputted is less than 10.
Assume we are using a scanner to allow a user to input any value they want.
I want the output string to display the hours minutes and seconds in HH:MM:SS with leading zeros if the value for any of variables entered is less than zero
Here is just a main method driver separate from entire main program as I am keeping code quarantined so that I don't get confused:
public class testString {
public static void main(String[] args)
{
// variables assume that i am allowing scanner input, in main project, for now using
// dummy values in place of scanner
int hours = 1;
int minutes = 6;
int seconds = 40;
// format string to be corrected as well with allowing leading zeros if value is less
// than 10
String output = String.format("%02d %02d %02", hours, minutes,
seconds);
System.out.println(output);
}
}
You forgot the last d
. Do it like this. To ensure the field has leading zeros, put a 0
before the width specifier.
String output = String.format("%02d:%02d:%02d", hours, minutes,
seconds);
System.out.println(output);
You can also do this by use the System.out.printf()
method.
System.out.printf("%02d:%02d:%02d%n", hours, minutes,
seconds);
For details, check out Formatter in the Java API.
I cannot find the proper syntax for a string format as well as setting it up for a output that adds the leading zeros IF the value inputted is less than 10.
Assume we are using a scanner to allow a user to input any value they want.
I want the output string to display the hours minutes and seconds in HH:MM:SS with leading zeros if the value for any of variables entered is less than zero
Here is just a main method driver separate from entire main program as I am keeping code quarantined so that I don't get confused:
public class testString {
public static void main(String[] args)
{
// variables assume that i am allowing scanner input, in main project, for now using
// dummy values in place of scanner
int hours = 1;
int minutes = 6;
int seconds = 40;
// format string to be corrected as well with allowing leading zeros if value is less
// than 10
String output = String.format("%02d %02d %02", hours, minutes,
seconds);
System.out.println(output);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.