我怎么能在JAVA
问题描述:
创建数字串
我要获得这个格式的字符串:我怎么能在JAVA
"000xxx"
一些示例:
int xxx = 10 -> result = "000010";
int xxx = 015 -> result = "000015";
int xxx = 100 -> result = "000100";
我可以使用哪些格式化为一个字符串?
答
您可以使用追加留下String.format
例如:
int myInt = 1;
String result = String.format("%06d", myInt);
输出
1 000001
10 000010
101 000101
+0
为什么你使用一个字符串,如果你Integer.parseInt它后无论如何:p – Nathan
+0
是的,我不知道什么OP使用类型,谢谢任何方式@Nathan –
答
System.out.format("%06d", n);
,其中n
是一个整数,应该工作正常进行您的格式。它看起来是6位宽度,带领0
's。与其他答案一样,如果您只是在寻找字符串,您可以仅执行String.format("%06d", n);
。
答
这可能会帮助;
static String getString(int xxx)
{
if(xxx > 0 && xxx < 1000)
return String.format("%06d", xxx);
return null;
}
答
public class Temp {
public static void main(String args[]) {
System.out.println(StringReturn.numToString(1));
System.out.println(StringReturn.numToString(10));
System.out.println(StringReturn.numToString(101));
}}
class StringReturn
{
static String numToString(int num){
return String.format("%06d", num);
}}
输出
000001
000010
000101
https://docs.oracle.com/javase/tutorial/java/data/numberformat.html –
第一次尝试。如果您遇到问题,请提出一个**特定的**问题,以及您将写入的(错误)代码。 – progyammer