Friday 15 May 2015

java - Checking if string value is a set of integers -



java - Checking if string value is a set of integers -

i trying take in string , check if values of string equal numbers between 1-9999 , homecoming error message otherwise. have seen , heard can utilize .isnumeric() or .matches() can't seem figure out how implement it. have far:

string yearstring; int year = 0; scanner input = new scanner(system.in); { system.out.println("please come in year of start date"); yearstring = input.nextline(); if (yearstring.matches("[1-9999]+")) { year = integer.parseint(yearstring); } else { system.out.println("please come in positive numbers only"); } } while (year <= 0);

if want regex approach, can utilize next regex instead of [1-9999]+ (which generates infinite numbers) : [1-9][0-9]{0,3}. means any string starting non-zero figure followed 3 or less figures.

a little test :

string regex = "[1-9][0-9]{0,3}"; int i; (i=0 ; string.valueof(i + 1).matches(regex) ; i++); system.out.println(i);

outputs 9999 expected. however, @uʍop ǝpısdn solution more readable may slower if there lot of invalid strings (exception have non negligeable cost) whereas regex approach not depend of this. if have lot of entries test, should compile pattern 1 time , utilize matcher :

pattern p = pattern.compile("[1-9][0-9]{0,3}"); int i; (i=0 ; p.matcher(string.valueof(i + 1)).matches() ; i++); system.out.println(i);

java

No comments:

Post a Comment