This is in java.
How do I validate that a users input is 4 digits (for my code it is supposed to be a year for example "2003" ); this is what I have in a class that is separate from the main
public class Album {
private String title;
private String artist;
private int releaseYear;
public Album (String title, String artist) {
this.title = title;
this.artist = artist;
this.releaseYear = 0;
}
public boolean setReleaseYear (String releaseYear) {
if (releaseYear.matches("(\\d{3})" )){
String cleanedReleaseYearString = releaseYear.replaceAll("(|\\-)"," ");
this.releaseYear = Integer.parseInt(cleanedReleaseYearString);
return true;
} else {
return false;
}
}
public String getReleseYear() {
String releaseYear = Integer.toString(this.releaseYear);
String digit = releaseYear.substring(0,3);
return " " + digit;
}
***BACK IN MAIN***
public class Main {
private static final String DATABASE_FILE_NAME = "database.txt";
private static ArrayList<Album> albumCollection = new ArrayList<Album>();
public static void main(String[] args) throws Exception {
boolean isReleaseYearSet = false;
while( !isReleaseYearSet ) {
System.out.println("Enter year album was released in the formal 2019: ");
String releaseYear = in.nextLine();
System.out.println(" ");
isReleaseYearSet = newAlbum.setReleaseYear(releaseYear);
}
}
I am taking the user input from the main class, and validating if it is a four digit numerical value (a year), It compiles but it continuously ask for input of year.
If you have any doubts, please give me comment...
The pattern that you are matching, that is incorrect. It matches only 3 digits. If 4 digits, it returns false. So that you have change for 4 digits.
Use this code in setReleaseYear method
if(releaseYear.matches("\\d{4}"))
This is in java. How do I validate that a users input is 4 digits (for...