0
public class Date 
{

   private int day,
               month,
               year;

   public Date(int day, int month, int year)
   {
      this.day=day;
      this.month=month;  
      this.year=year;   
   }

   public int getday()
   {  
       return day;    
   }

   public int getmon()
   {
       return month;  
   }

   public int getyear()
   {
         return year;   
   }

   public void setd(int day)
   {

      this.day=day;
   }

   public void setm(int month)
   {

      this.month=month;
   }

   public void sety(int year)
   {

      this.year=year;
   }

   public String toString()
   {
      return " "+getday()+"/"+getmon()+"/"+getyear();
   }
}

How to make the toString method to return 2 leading 0? So that if I call it in the main if I call the toString method it will print

The output of that is 2/10/199

my expected output

02/10/1999

Roman
  • 4,922
  • 3
  • 22
  • 31
sireee
  • 106
  • 9
  • As an aside, if you're writing a `Date` class as an exercise, that's a fine exercise. For production code one would never do it but would use the built-in `LocalDate` class. – Ole V.V. Dec 27 '19 at 07:48
  • Welcome to Stack Overflow. Please learn to search before asking a new question. Chances are that your question has been asked before and that you will find a wealth of good answers without having to wait for someone to write a new answer. – Ole V.V. Dec 27 '19 at 07:56

1 Answers1

2

Replace your function with String.format()

public String toString()
   {
      return " "+String.format("%02d", getday())+"/"+getmon()+"/"+getyear();
   }

Sample output

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

papaya
  • 1,505
  • 1
  • 13
  • 26