[英]String formatter IF the value is less than 10 add the leading zeros java in HH:MM:SS format with 3 variables syntax
如果输入的值小于 10,我找不到字符串格式的正确语法,也无法为添加前导零的 output 设置它。
假设我们正在使用扫描仪来允许用户输入他们想要的任何值。
如果输入的任何变量的值小于零,我希望 output 字符串以 HH:MM:SS 格式显示小时、分钟和秒,前导零
这只是一个与整个主程序分开的主方法驱动程序,因为我将代码隔离开,以免混淆:
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);
}
}
你忘了最后一个d
。 像这样做。 为确保该字段有前导零,请在宽度说明符前放置一个0
。
String output = String.format("%02d:%02d:%02d", hours, minutes,
seconds);
System.out.println(output);
您也可以使用System.out.printf()
方法来执行此操作。
System.out.printf("%02d:%02d:%02d%n", hours, minutes,
seconds);
详情请查看 Java API 中的Formatter 。
如果输入的值小于 10,我无法找到字符串格式的正确语法,也无法将其设置为添加前导零的输出。
假设我们使用扫描仪来允许用户输入他们想要的任何值。
如果输入的任何变量的值小于零,我希望输出字符串以 HH:MM:SS 显示小时分和秒,并带有前导零
这只是一个与整个主程序分开的主要方法驱动程序,因为我正在隔离代码以免混淆:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.