Solved

Checking strings for a only numbers

Posted on 2004-10-24
371 Views
Last Modified: 2010-04-01
I need to know if there is a method associated with a class that simply checks wheter a string contains only numbers(these numbers are 0-7). If not, can someone post some code that will tell me how check a string for a value of 0-7? Thanks in advance!


0
Question by:kewel
    11 Comments
     
    LVL 13

    Accepted Solution

    by:
    Try this:

      public static void main(String[] args)
      {
        Class1 class1 = new Class1();
        String tested ="03444532";
        boolean bool = class1.checkString( tested);
        System.out.println(bool);
       
      }
     
      public boolean checkString(String tested)
      {
        String allowedChars = "01234567";
        for(int i=0; i < tested.length() ; i++)
        {
          char aChar = tested.charAt(i);
          if( allowedChars.lastIndexOf(aChar) == -1 )
          {
            return false;
          }
        }
        return true;
       
      }
    0
     
    LVL 21

    Expert Comment

    by:MogalManic
    How about this:

    public boolean isNumber()
    {
     try {
       Integer.valueOf(str)
       return true;
     } catch (NumberFormatException x)
       return false;
     }
    }
    0
     
    LVL 13

    Expert Comment

    by:petmagdy
    this will not do it MogalManic because not all numbers are allowed just from 0 to 7, right kewel?
    0
     
    LVL 3

    Assisted Solution

    by:gnudiff
    If the check needs to be done only for 0-7, then MogalManic's script needs to be changed only slightly:

    public boolean isNumber()
    {
     try {
       int i=Integer.parseInt(str, 8);
       return true;
       }
      catch (NumberFormatException x)
      {
           return false;
      }
    }
    0
     
    LVL 21

    Assisted Solution

    by:MogalManic
    OOPS.  Did not read closly enough.

    This would work:
          public boolean isNumber(String num)
          {
                return num.matches("[0-7]+");
          }
    0
     
    LVL 27

    Assisted Solution

    by:rrz
    How about this method?

         public static boolean isNumber(String var){
                              for(int i=0;i<var.length();i++){
                                       char c = var.charAt(i);
                                       if(!Character.isDigit(c)){return false;}
                                         else{if(c=='8'||c=='9')return false;}
                              }
                              return true;
         }
    0
     
    LVL 2

    Assisted Solution

    by:arnon81
    Hi

    Use this method, it will solve your problem
    isDigit will return true if str contains number 0-7 only.
    public static boolean isDigit(String str)
          {
                if (str==null)
                {
                      return false;
                }
                str=str.trim();

                if (str.equals(""))
                {
                      return false;
                }
                char[] temp = str.toCharArray();
                boolean isdigit=true;

                for (int i=0;i<temp.length ;i++ )
                {
                      if (!Character.isDigit (temp[i]))
                      {
                            isdigit=false;
                      }
                      else
                      {
                            if (Integer.parseInt(""+temp[i])<0 && Integer.parseInt(""+temp[i])>7))
                                  isdigit=false;

                      }
                      
                      
                }
                return isdigit;
          }

    Sincerely,
    Arnon
    0
     
    LVL 29

    Assisted Solution

    by:bloodredsun
    I suggest using regular expressions. Much shorter and more powerful

    public static boolean isDigit(String final str){
         return str.matches( "([0-7]*)" ) ;
    }

    this would also allow you to check the length or incidence of certain numbers if that were important

    public static boolean isDigit(String final str){
         return str.matches( "([0-7]{1,9})" ) ;
    }

    Str must be all 0 to 7 and must be between 1 and 9 in length (number of times the pattern occurs) in the above code
    0
     
    LVL 3

    Expert Comment

    by:gnudiff
    Regexps are generally very good, I agree.

    However, if the task is simply to check for digits 0-7, then using a regexp is an overkill; I have an (untested) suspicion that a regexp is a magnitude more resource intensive than a parseInt().
    0
     
    LVL 29

    Expert Comment

    by:bloodredsun
    I have to disagree with gnudiff. I've used regexp quite often and the power they bring is NOT at the expense of overhead (in my opinion admittedly). These pieces of code are optimised so that they take the smartest route to finding the solution and as a rule it's always better to take advantage of the standard api methods rather than role your own. They are also easier to extend and maintain . Imagine if the string gets changed so that it gets pre-fixed with 3 lowercase alphabetic charater, due to expansion requirements, the regexp changes from "([0-7]*)" to "([a-z]{3}[0-7]*)", which is hardly tough.

    It is the fact that they are so much more complex to write the first time you use one tends to put people off, but to be honest, go with whatever you feel most comfortable with as it's what you'll use again and again.
    0
     
    LVL 3

    Expert Comment

    by:gnudiff
    Well, it is the specifics of the case.

    Whenever we are talking general string manipulation, there can be tons of ways of using a regexp effectively. And there I would agree with you completely. I like regexps myself, and a regexp is frequently (due to internal optimization) better than lots of String functions.

    However, I will have a hard time believing the regexp engine itself could be more efficient than a simple internal

    int i=Integer.parseInt(str, 8);

    If it is, then I think the Java engine is in serious need of optimization.
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone. Privacy Policy Terms of Use

    Featured Post

    Highfive + Dolby Voice = No More Audio Complaints!

    Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

    Previously, we learned about how professional data recovery experts can recover lost data from a damaged or compromised hard drive (https://www.experts-exchange.com/articles/28564/What's-Possible-with-Modern-Data-Recovery.html). Below, you will find…
    Today, still in the boom of Apple, PC's and products, nearly 50% of the computer users use Windows as graphical operating systems. If you are among those users who love windows, but are grappling to keep the system's hard drive optimized, then you s…
    This video Micro Tutorial is the second in a two-part series that shows how to create and use custom scanning profiles in Nuance's PaperPort 14.5 (http://www.experts-exchange.com/articles/17490/). But the ability to create custom scanning profiles a…
    Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…

    877 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    13 Experts available now in Live!

    Get 1:1 Help Now