Checking strings for a only numbers

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!


kewelAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

petmagdyCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MogalManicCommented:
How about this:

public boolean isNumber()
{
 try {
   Integer.valueOf(str)
   return true;
 } catch (NumberFormatException x)
   return false;
 }
}
0
petmagdyCommented:
this will not do it MogalManic because not all numbers are allowed just from 0 to 7, right kewel?
0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

gnudiffCommented:
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
MogalManicCommented:
OOPS.  Did not read closly enough.

This would work:
      public boolean isNumber(String num)
      {
            return num.matches("[0-7]+");
      }
0
rrzCommented:
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
arnon81Commented:
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
bloodredsunCommented:
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
gnudiffCommented:
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
bloodredsunCommented:
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
gnudiffCommented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JSP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.