#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2010
    Posts
    11
    Rep Power
    0

    Read user input and check if it is integer


    Hello all,

    im trying to work out how to check if part of a string the user has inputted is an integer or not. i know little bits of java so im not a complete novice. so i know of things like startsWith().

    Basically, the general idea i have is to take user input, and check that it fits the skeleton G<int><int><int> (eg G001). As you can see below, i can do it with G as it's straightforward, but not really sure how to check if the next 3 parts are integers. I think maybe have a for loop elsewhere in the class that goes through the numbers 0-9 and checks that against the if statement below? or declare a variable like inputCheck[] = {0,1,2,3,4,5,6,7,8,9}? Ive tried this partially but my understanding doesnt give me error-free results. Any help would be greatly appreciated!

    Code:
    System.out.println("Please enter the CustomerID: "); 
    line = reader.readLine();
     if (line.getText().startsWith("G") && line.getText().startsWith("", 1) && line.getText().startsWith("", 2) && line.getText().startsWith("", 3) ) { 
    ; 
    }
    Thanks
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,040
    Rep Power
    1291
    Have you thought about a regular expression?
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2010
    Posts
    11
    Rep Power
    0
    could you please expand?
  6. #4
  7. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,040
    Rep Power
    1291
    If you take a look at the java.util.regex.Pattern class, you can see a description of some of the patterns you can use with regular expressions. It's a large topic, but there are parts of it that will easily let you do what you want to do.

    Comments on this post

    • Yawmark agrees
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2010
    Posts
    11
    Rep Power
    0
    thanks a lot for the help guys!

IMN logo majestic logo threadwatch logo seochat tools logo