Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Checking strings for a only numbers

Posted on 2004-10-24
13
Medium Priority
?
377 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
Comment
Question by:kewel
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +3
13 Comments
 
LVL 13

Accepted Solution

by:
petmagdy earned 140 total points
ID: 12394915
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
ID: 12396945
How about this:

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

Expert Comment

by:petmagdy
ID: 12398122
this will not do it MogalManic because not all numbers are allowed just from 0 to 7, right kewel?
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 3

Assisted Solution

by:gnudiff
gnudiff earned 132 total points
ID: 12398589
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
MogalManic earned 132 total points
ID: 12398656
OOPS.  Did not read closly enough.

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

Assisted Solution

by:rrz
rrz earned 132 total points
ID: 12400632
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
arnon81 earned 132 total points
ID: 12528507
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
bloodredsun earned 132 total points
ID: 12862584
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
ID: 12871013
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
ID: 12871569
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
ID: 12876646
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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It’s time for spooky stories and consuming way too much sugar, including the many treats we’ve whipped for you in the world of tech. Check it out!
Are you looking for the options available for exporting EDB files to PST? You may be confused as they are different in different Exchange versions. Here, I will discuss some options available.
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Suggested Courses

636 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