Question

This is in java. How do I validate that a users input is 4 digits (for...

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.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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}"))
Add a comment
Know the answer?
Add Answer to:
This is in java. How do I validate that a users input is 4 digits (for...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT