• Post Reply Bookmark Topic Watch Topic
  • New Topic

smart way to check that input is integer  RSS feed

 
Maha Hassan
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi All
i need to find a way to check that the user input is a list of number ex[ 23 -34 -55 56 57 ]
only numbers , spaces and - are allowed
is there a smart way to solve this
thanks
 
Manuel Moons
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use a regular expression for this. Take a look at the "java.util.regex" package. The sun tutorial might be useful.
Sun Regular expression lessons
 
aven kimball
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for posting that link.
I am testing this example. I have jdk 1.4.2_08. But it gave me the error package
java.util.regex do not exit. The tutorial also saying that
Before continuing with the next section, save and compile this code to ensure that your development environment supports the java.util.regex package. . So how to make it available?
 
Ali Hussain
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi All
i need to find a way to check that the user input is a list of number ex[ 23 -34 -55 56 57 ]
only numbers , spaces and - are allowed
is there a smart way to solve this
thanks


You can use Character.isDigit method...


if (char = '-' | char = ' ' | Character.isDigit(char))...
 
Jean-Sebastien Abella
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s = " 90";
int i = 0;
try
{
i = Integer.parseInt(s.trim());
}catch( NumberFormatException nbe)
{
//you know it's not ok!
}
 
fdafd fdafda
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you want to check the input is a list of integers separated by space. Checking char one by one is not sufficient. it doesnt catch the case of [12 --13 14]
I would suggest you split the string into a string array and check them one by one.

the following method should return true for list [12 13 -14 15 -16] but false for [12 - 13 --14 15 16]

public boolean numList(String input)
{
String pattern= "[-]?[0-9]+";
String[] sLine=input.split(" ");
for(String sTemp: sLine)
{
if (!sTemp.matches(pattern)&&!(sTemp.equals("")))
return false;
}
return true;
}
[ August 09, 2005: Message edited by: Lucas Jiang ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!