Computer Science Canada

VerifyString class, test for all numbers or all letters!

Author:  the_short1 [ Wed May 03, 2006 9:46 am ]
Post subject:  VerifyString class, test for all numbers or all letters!

Tired of having to say "dont enter numbers into string, or visa versa, when getting input from user" in your programs? Or having long if statements to check for validity of input in every program. Me too! So try this class I just made.

Purpose:
To 'verify' a string as all numbers (safe to pass to Integer.parseInt).
To 'verify' a string as all letters/punctuation (good for valid names).
To 'verify' a string as not ""(null), or " "(starting with whitespace).

To start:
Download Verify.java into the folder where your code is stored
Add "import Verify.*;" to the top of your code
OR
"public class YourClassName extends Verify {"

Returns:
True or False (boolean)

To Use:
-If you want to check for all numbers,
"If (Verify.allNum (aString) == true)"
This will return TRUE, if aString contains all numbers, eg "1337"

-If you want to check for all letters,
"If (Verify.allLetters (aString) == true)"
This will return TRUE, if aString contains all letters/punctuation, eg "Kevin's Code"

-If you want to check for null/whitespace at start,
"If (Verify.allLetters (aString) == false)"
This will return FALSE, if aString is ""(null) or " " or " words" or " 990"

I attached the Verify code, and an example file which demonstrates its use.

If you find a bug/have any questions or comments, let me know.

-Kevin


Edit: Fixed a small bug from null entries from joptionpane (if you pressed cancel), it didnt return false, now it does.. . although its always returned false if you entered nothing and pressed 'ok'

Author:  wtd [ Wed May 03, 2006 10:57 am ]
Post subject: 

I would suggest you create a public interface:

code:
public interface StringVerificationPredicate {
   public boolean verifies(String s);
}


Then define a StringVerification class like so:

code:
public class StringVerification {
   public static boolean all(String s, StringVerificationPredicate p) {
      for (int i = 0; i < s.length; ++i) {
         if (p.verifies(s))
            return false;
          }
          
          return true;
   }

   // Define your all* methods in terms of all.
}


: