4

Is it possible to allow only letters or numbers in a string in java ? for example :

String Text;
Text = jTextField1.getText();

now

if (Text is a number) {System.out.println("Invalid Input");}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Loop Masters
  • 371
  • 2
  • 5
  • 12
  • Hint: Stick to common naming conventions and make fields and variables lowercase (i.e. `Text` in your case). – Howard Jun 17 '12 at 11:29
  • Please have a look at this [example](http://stackoverflow.com/questions/9477354/how-to-allow-introducing-only-digits-in-jtextfield/9478124#9478124), also, simply replace `if (Character.isDigit(text.charAt(len - 1)))` with `if (!Character.isDigit(text.charAt(len - 1)))` and I guess it will work for your scenario as well :-) – nIcE cOw Jun 17 '12 at 12:40

2 Answers2

10

you have two choices to use


  • notice don't use String Text; (possible reserved word for API name or its method) use String text; more in the Naming convention
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

Addition: You could do it also like the following, though i recommend mKorbel's answer.

try  {
    System.out.println(Integer.parseInt(Text) + "is a valid input.");
} catch (Exception e) {
    System.out.println("The input "+ Text + "is invalid");
}
shidizzle
  • 55
  • 1
  • 1
  • 10