destroted
destroted

Reputation: 51

Checking if string value is a set of integers

I am trying to take in a String and check if the values of the string are equal to numbers between 1-9999 and return an error message otherwise. I have seen and heard that I can use .isNumeric() or .Matches() but I can't seem to figure out how to implement it. This is what I have so far:

String yearString;
int year = 0;
Scanner input = new Scanner(System.in);

do {
    System.out.println("Please enter the year of the start date");
    yearString = input.nextLine();

    if (yearString.matches("[1-9999]+"))
    {
        year = Integer.parseInt(yearString);
    }
    else
    {
        System.out.println("Please enter positive numbers only");
    }

} while (year <= 0);

Upvotes: 2

Views: 226

Answers (2)

Dici
Dici

Reputation: 25950

If you want a regex approach, you can use the following regex instead of [1-9999]+ (which generates infinite numbers) : [1-9][0-9]{0,3}. This means any String starting with a non-zero figure followed by 3 or less figures.

A little test :

String regex = "[1-9][0-9]{0,3}";
int i;
for (i=0 ; String.valueOf(i + 1).matches(regex) ; i++);
System.out.println(i);

Outputs 9999 as expected. However, @uʍop ǝpısdn solution is more readable but may be slower if there are a lot of invalid strings (exception have a non negligeable cost) whereas the regex approach does not depend of this. If you have a lot of entries to test, you should compile your pattern only once and use a Matcher :

Pattern p = Pattern.compile("[1-9][0-9]{0,3}"); 
int i;
for (i=0 ; p.matcher(String.valueOf(i + 1)).matches() ; i++);
System.out.println(i);

Upvotes: 2

salezica
salezica

Reputation: 76899

This expression:

[1-9999]+

Means "match a number from 1 to 9, or a 9, or a 9, or a 9". Each 9 is taken separately.

You can correct that regex, but it's easier to conver the number to an integer and check for its validity afterwards.

boolean isValid(String numericString) {
    try {
        int number = Integer.parseInt(numericString);
        return number > 0 && number <= 9999;

    } catch (NumberFormatException e) {
        return false;
    }
}

Upvotes: 2

Related Questions