Java 如何在toString()方法中返回2前导0? 公开课日期 { 私人国际日, 月, 年份; 公开日期(整数天、整数月、整数年) { 这个.天=天; 本月=月; 今年=年; } public int getday() { 回归日; } 公共int getmon() { 返回月份; } 公共int getyear() { 回归年; } 公共无效设置(整数天) { 这个.天=天; } 公共无效setm(整数月) { 本月=月; } 公共假期(整年) { 今年=年; } 公共字符串toString() { 返回“+getday()+”/“+getmon()+”/“+getyear()”; } }

Java 如何在toString()方法中返回2前导0? 公开课日期 { 私人国际日, 月, 年份; 公开日期(整数天、整数月、整数年) { 这个.天=天; 本月=月; 今年=年; } public int getday() { 回归日; } 公共int getmon() { 返回月份; } 公共int getyear() { 回归年; } 公共无效设置(整数天) { 这个.天=天; } 公共无效setm(整数月) { 本月=月; } 公共假期(整年) { 今年=年; } 公共字符串toString() { 返回“+getday()+”/“+getmon()+”/“+getyear()”; } },java,date,oop,Java,Date,Oop,如何使toString方法返回2前导0?因此,如果我在main中调用它,如果我调用toString方法,它将打印 其输出 2/10/199 我的预期输出 02/10/1999用String.format()替换函数 样本输出 getDay(); //prints "1" String.format("%02d", getday()); //prints "01" 用String.format()替换函数 样本输出 getDay(); //prints "1" String.format("%

如何使
toString
方法返回2前导0?因此,如果我在main中调用它,如果我调用
toString
方法,它将打印

输出 2/10/199

我的预期输出


02/10/1999

用String.format()替换函数

样本输出

getDay(); //prints "1"
String.format("%02d", getday()); //prints "01"


用String.format()替换函数

样本输出

getDay(); //prints "1"
String.format("%02d", getday()); //prints "01"


左侧的这个检查按钮?是的@sireeyour也可以这样做
NumberFormat strFormat=new DecimalFormat(“00”);标准格式(22)//打印“22”标准格式(21);//打印“01”
我会全部打印:
String.format(“%02d/%02d/%d”,getday(),getmon(),getyear())
。左侧的这个检查按钮?是的@sireeeYour也可以这样做
NumberFormat strFormat=new DecimalFormat(“00”);标准格式(22)//打印“22”标准格式(21);//打印“01”
我会全部使用:
String.format(“%02d/%02d/%d”,getday(),getmon(),getyear())
。另外,如果您将
Date
类作为练习编写,这是一个很好的练习。对于生产代码,您永远不会这样做,而是使用内置的
LocalDate
类。欢迎使用堆栈溢出。在问新问题之前,请先学会搜索。有可能你的问题以前被问过,你会找到大量好的答案,而不必等待别人写新的答案。顺便说一句,如果你写一个
日期
课程作为练习,那是一个很好的练习。对于生产代码,您永远不会这样做,而是使用内置的
LocalDate
类。欢迎使用堆栈溢出。在问新问题之前,请先学会搜索。有可能你的问题以前被问过,你会找到大量好的答案,而不必等待别人写一个新的答案。