甚至可以在带有terny运算符的java中添加0吗? [英] is it even possible to add a 0 in java with terny operators?
本文介绍了甚至可以在带有terny运算符的java中添加0吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨我已经尝试过terny运算符,if else语句和解析int到字符串的所有内容,我正在制作一个读取4:01 4:02的时钟,但它输出4:1
Hi I've tried everything from terny operators, if else statements and parsing the int to a string, I am making a clock that reads 4:01 4:02 but instead it outputs 4:1
这是我的java代码,是否可以添加0?或者我还需要别的东西?
this is my java code, is it possible to add a 0? or I am going to need something else?
package bank;
import java.util.*;
/**
*
* @author will
*/
public class dClock {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Calendar time = Calendar.getInstance();
int min = 1;//time.get(Calendar.MINUTE);
int hour = time.get(Calendar.HOUR_OF_DAY);
int blank = Integer.parseInt("0");
int hourOfDay = ((hour > 12) ? (hour - 12) : hour);
int zero = ((min > 10 ) ? min : blank+min);
System.out.println("The time is " + hourOfDay + ":" + zero );
}
}
推荐答案
您只需使用 String.format(模式,数据)
,模式为%02d
-
%
代表模式开始 -
2
表示输入应至少写成两个字符__
-
0
但是如果输入短于两个字符,则用0填充休息
_a
- >0a
-
d
很短来自数字
%
represents start of pattern2
means that input should be written as at least two characters__
0
but if input is shorter than two characters fill rest with0
_a
->0a
d
is short from digit
这意味着数字传递的数字应该用两个字符写,如果有空格(数字也是简短如 0
, 1
, 2
直到 9
)用 0
填充前面的空格。
which all means that digit passed digit should be written using two characters and in case there would be empty space (number is too short like 0
, 1
, 2
till 9
) fill space before it with 0
.
演示:
String formatted = String.format("%02d:%02d", 4,2);
System.out.println(formatted);
输出: 04:02
这篇关于甚至可以在带有terny运算符的java中添加0吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文