I'm creating a phone directory which will consist of multiple nameEntry
objects each containing a surname and a phone extension.
public class nameEntry {
public String surname;
public String number;
public nameEntry(String surname, int number) {
this.surname = surname.toUpperCase();
this.number = String.format("%04d", number);
// converts int literal to 0 filled string of numbers
}
public String toString() {
return surname + "\t" + number; //eg HOOD 0123
}
}
Having read into good java practice about storing alphanumerics I have programmed the nameEntry
objects to take an int
as a parameter and then convert it to a zero filled String
, because storing as int
Objects would be inappropriate given their nature. However, this approach means that I cannot create new nameEntry
objects with zero filled numbers by this method as it tells me the integers are invalid;
nameEntry e = new nameEntry(surname, 0123); //this would be flagged as wrong
However if I use a Scanner nextInt(System.in)
method, is it perfectly happy with me entering a zero filled digit and then using that object to create a new nameEntry
object.
Why is this scenario valid?
Regardless, this all seems over the top just to get a single zero filled input string - what is a better way of allowing a user to enter a single number of up to 4 characters that is either zero filled, or will be automatically zero filled after entry?