• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 379
  • Last Modified:

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!


0
kewel
Asked:
kewel
  • 3
  • 2
  • 2
  • +3
6 Solutions
 
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
 
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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Featured Post

Take Control of Web Hosting For Your Clients

As a web developer or IT admin, successfully managing multiple client accounts can be challenging. In this webinar we will look at the tools provided by Media Temple and Plesk to make managing your clients’ hosting easier.

  • 3
  • 2
  • 2
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now