RarkMowe
RarkMowe

Reputation: 77

Limiting the length of an input to x amount of digits

I'm running a java program I created that stores data inputted by user. Specifically 4 array lists which are songName, songArtist, songYear & songAlbum. I have a user input for "songYear" and I only want the program to accept a maximum of 4 digits in length and give an error otherwise, how can this be achieved? Here's a screenshot

here's the code I have for my add entry method:

        public void addEntry(){
        String newName = ui.getString("Enter the name of the track");
        songName.add(newName);
        String newArtist = ui.getString("Who performs this track");
        songArtist.add(newArtist);
        String newAlbum = ui.getString("What album is this track from");
        songAlbum.add(newAlbum);
        System.out.print("What year was the track released? ");
        int newYear=input.nextInt(4);
        songYear.add(newYear);

        System.out.println("\n" + "Thank you, " +songName.get(songName.size()-1) + " has been added to the library.");
        System.out.println("\n" + "Press 2 to view your library." + "\n");
    } 

Upvotes: 0

Views: 8425

Answers (3)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

You can use regex like: ^.{4}$

Means only if user typed 4 digits - return true, otherwise return false

To be sure that user used 4 numbers YYYY use something like:

^(?=[1-9]+)\d{4}$

Makes sure the year is 1 or 2 followed by three numbers; valid ranges in this case would be 1000-2999

^(?=[1-2][0-9]+)\d{4}$

Finally your code should be like:

 if(inputUserStr.matches("^(?=[1-2][0-9]+)\d{4}$")){
   // do some stuff
 }
  else{
   // print error about valid input form [YYYY]
  }

Upvotes: 2

agirish
agirish

Reputation: 470

1) Accept the user's input and using the substring method, save only the first four characters (Specify to user that first 4 characters are considered).

2) You can ask the user to reenter the value if it is not 4 characters:

Scanner sc = new Scanner(System.in);

String a = sc.next();
        if (a.matches("...."))
        {
             System.out.print(a);
        }
            else 
        {
             System.out.print("Input again:" );   
             a = sc.next();
        }

I've written a sample regex for 4 characters. But you can always change it.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881653

Depends entirely on the language but some approaches are:

  • check the string input using a len function; or
  • convert it to an integer and ensure it's less than 10,000; or
  • a regular expression like ^\d{1,4}.

No doubt there'll be other validation checks such as ensuring string input is all-numeric, and you're not trying to input a song that was written twenty years in the future, but they're added checks you should consider.

Upvotes: 0

Related Questions