Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Check to see if a String contains words only?

 
Jamie Cotton
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hiya all

I wanna check if a variable value is words only or not.
So if I had


so test should only be allowed to be something like "hello" and not something like "123". If "123" appears I want it to tell me.

Such as if i wanna check if the value is an interger I would do Interger.parseInt(String test). If test = 123 then it would be ok but if test = "hello" if would throw an exception.
[ April 09, 2005: Message edited by: Jamie Cotton ]
 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Such as if i wanna check if the value is an interger I would do Interger.parseInt(String test). If test = 123 then it would be ok but if test = "hello" if would throw an exception.


Jamie,
Try:

String test = " ";
test = String.parseString(test);
 
Jamie Cotton
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried that but still no luck
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jamie Cotton:
I tried that but still no luck


Not surprising, considering there is no such method!

There's no method in the API which will tell you directly whether a String is a "word" because word-ness is a subjective concept. On the other hand, testing for integer-ness is straightforward.

The first thing you need to do is to state your problem clearly. Are you interested in a JTextField which allows you to type only alphabetic characters? That's doable. Are you interested in telling whether a String contains any digits? That's doable, too. But you have to think clearly about exactly what you want to do, and so far, you haven't made a precise statement of what that is.
 
Jamie Cotton
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry I am interested in a JTextField which allows you to type only alphabetic characters.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, that's easy. Use a JFormattedTextField, which lets you specify the format for legal data entries. See Here for a tutorial on using this class, including demo code.
 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
or you could experiment with regular expressions
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic