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

    Join Date
    Nov 2017
    Posts
    5
    Rep Power
    0

    How to write this Boolean method


    Hi guys

    My method is as follows

    public Boolean digitsValid (String s)

    The string returns true if its length is equal to 6, but false if not. I need advice on how to make the expression return true if all the characters after char[0] are digits
    and false otherwise.

    e.g. X45678- True .............Xrw345 -False


    Any help appreciated
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jul 2003
    Posts
    4,392
    Rep Power
    631
    java Code:
     
    public boolean digitsValid(String s) {
    		if (s.length()!=6) {
    			return(false);
    		}
    		return(s.matches("\\D\\d+")) 
    	}

    Not tested but should be close.
    Last edited by gw1500se; November 25th, 2017 at 07:07 AM.
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2017
    Posts
    5
    Rep Power
    0
    Thanks for the reply. Does this calculate the lengths & whether the inputs after the first input are digits?
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jul 2003
    Posts
    4,392
    Rep Power
    631
    The 'if' statement will assure the length is 6 otherwise return false. The 'matches' statement returns true only if the first character of the string is a non-digit and all the remaining characters ARE digits. If you like really small methods you can use this:
    java Code:
     
    public boolean digitsValid(String s) {
    		return(s.length()==6 && s.matches("\\D\\d+")) ;
    	}
    Last edited by gw1500se; November 25th, 2017 at 09:06 AM.
    There are 10 kinds of people in the world. Those that understand binary and those that don't.

IMN logo majestic logo threadwatch logo seochat tools logo