• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

How to check if String() value is numeric

 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Do you mean like the ATTACHED type in Eiffel?


Quite possibly. Unfortunately, Eiffel is one of those languages that I've heard a lot about but never used.

Winston
 
Marshal
Posts: 74006
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Eiffel? I once tried to write a compiler for it.
It used to be really popular, particularly in the late 1980s and 1990s. A really good language for learning object‑orientation (OO). Bertrand Meyer plugged it as a reliable language; it has keywords which cause Exceptions to be thrown if a class invariant is breached, or a loop variant doesn’t alter, etc. It is fully OO, even things like INTEGER being full‑blown objects. Unfortunately it has a context‑sensitive grammar, and about 2005 there were major changes to the language specification and many of its supporters deserted it. If you look at old Tiobe indices, you can watch it fall gradually from 15th position to the limbo of “not graded because the differences are too slight” in the >50 category.
 
Greenhorn
Posts: 6
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
iterate the string using charAt(index) and for each char ch:
Character.isDigit(ch)
 
Master Rancher
Posts: 4027
53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Vaishali Kulkarni - Boston wrote:iterate the string using charAt(index) and for each char ch:
Character.isDigit(ch)


Yes, that was the first thing Campbell suggested in the very first response.

Seven years ago.
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I prefer to use the scanner method if you are using the command line method

If on the other hand if you are using GUI then the parse method would be bettered used

 
Mike Simmons
Master Rancher
Posts: 4027
53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Really? Why is that?
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
change it to lowercase, then extract each character.
check the unicode(or ascii, i'm not sure which, but i think its unicode) of each character, to see if it falls in the range 48-57.
this can be done by
char c=string.charAt(1);//example
int x=c;
if(x<=48)&&(x>=57)
{
counter++;
}
if the counter=string.length(), its a number, as each character is a number
I hope this helps!
 
Mike Simmons
Master Rancher
Posts: 4027
53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Um, yes. I think that's been suggested a few times now. Except this version has some fatal bugs; it won't count anything.
 
Campbell Ritchie
Marshal
Posts: 74006
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why are you changing the char to an int? Also using the number literals 48 and 57 is error‑prone. You should use char literals.
 
Mike Simmons
Master Rancher
Posts: 4027
53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, I was referring more to the fact that the inequalities are completely backwards.
 
Campbell Ritchie
Marshal
Posts: 74006
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I wasn’t referring to the >= etc; that is a different error which will definitely cause problems. There is another feature about that line which I noticed and have kept quiet about, but which the compiler won’t keep quiet about.
 
Mike Simmons
Master Rancher
Posts: 4027
53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yeah, this code has many problems.

In comparison, Character.isDigit() simply works.
 
Campbell Ritchie
Marshal
Posts: 74006
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mike Simmons wrote: . . . Character.isDigit() . . .

I had forgotten about that. Even though I would appear to have been the first person to mention it on this discussion!
 
Sheriff
Posts: 26773
82
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mike Simmons wrote:In comparison, Character.isDigit() simply works.



And not only does it Just Work, it works better because it identifies "٢" as a digit. It doesn't restrict itself to just Latin digits, in other words.

(In case you don't recognize that character, it's the Arabic digit 2.)

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Regular expressions is your answer
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you can use regular expression.[0-9]
 
imed joseph
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

imed joseph wrote: you can use regular expression.[0-9]
       
       String str = "98989896";
       Pattern pattern = Pattern.compile("[0-9]");
       Matcher  matcher = pattern.matcher(str);

 
Campbell Ritchie
Marshal
Posts: 74006
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch

I believe your regex will not work. A few weeks ago I posted something for finding whether a String was all letters, and you can use that with slight changes to find whether your String is all numeric. Of course, some Strings containing all digits probably don't fulfil people's usualy concept of a number, and hegative numbers fractions will not be found like that.
This is probably not a usual format for a number, but will be found by the technique with a Stream: "00000000000000000000000".
 
Greenhorn
Posts: 5
VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I could to it so:



Bob Robertson wrote:Hello,

I have a situation where I want to validate whether the value passed in as a String() is a numeric v. alpha/special char value.  The process that will consume this data post-validation will be expecting numeric values.

Can someone give me a hint with how to do this without using a NumberFormatException?  If the Exception is encountered the only recovery necessary will be to log the data that needs to be reviewed since the data is subjective and cannot be modified at runtime based on any conditions.  I could just try to catch a NFE when trying to convert the value to an integer and then log that that data needs to be eye-balled, but I was hoping to do something a little more purdy.

If I were to use the java regex uitils, would I be provided a means to eliminate all alpha and special characters?

Just looking for a thums-up/thumbs-down or a possible alternative.

Thanks!    

bo-bizzle po-pizzle

 
Campbell Ritchie
Marshal
Posts: 74006
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That would work, but it doesn't look a very elegant solution. You can easily check the digits with > '0' or < '9', because if you look at this Unicode/ASCII table, you will see that 0123456789 are consecutive. You will also see that I should have used ≤ and ≥ not > and <. You could also use “not”:-
!(c < '0' && c > '9').
Let's have a look at how you might do it with a Stream:-This ’ is \u2019.

You can get an IntStream from a String with its chars() method (actually inherited from CharSequence). That Stream goes through each char as if cast to an int. You can use its allMatch() method which will stop execution whenever it hits a false. Note the indentation: the .s align vertically.
The IntPredicate required by allMatch is replaced by a λ expression, in this case testing whether the int called i is in the range 0...9.

Your technique will match the following text:-

0
0000000000000
00000000000001
1234567890
123456789012346789012345689012345678901234567890

and won't match

-1
-0
-1234567890

I would still preferorRemember that a Scanner has these three methods: 1 2 3.

I am pretty sure some of this has been discussed earlier in the thread or here.

It all goes to show how useful old threads can be,
 
Ranch Hand
Posts: 91
Eclipse IDE Debian Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry I posted too quickly. But this is one of the methods you can use. I know you don't want this way but if you do then this is the way. Sorry.

 
Campbell Ritchie
Marshal
Posts: 74006
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mark Ii wrote:. . . this is the way. . . .

I am afraid I would disagree. You are using exceptions for control flow in lines 5‑9. Rather than using that awkward construct if (b) … { … something … } else { … somethingDifferent … } in lines 20‑24., have a look at the old Sun style guide. WriteThe name of your method is confusing: all Strings are Strings. The String "12345" is still a String.

I still think the use of a method of Scanner or finding a regex for decimal numbers would be a better solution. I challenge you to work out what the difference between a regex and Scanner#hasNextDouble() would be. Maybe there isn't a difference to find.
 
Mark Ii
Ranch Hand
Posts: 91
Eclipse IDE Debian Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi! Mr. Ritchie how about the following code? What do you think? Please feel free to let me know.



 
Saloon Keeper
Posts: 8578
71
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Do you allow:
  • a leading plus (+)
  • a number that begins with a period (.)
  • a number that will overflow some storage range
  • exponents
  •  
    Campbell Ritchie
    Marshal
    Posts: 74006
    332
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Better, but please take notice of what Carey said.
    If somebody passes null, don't return false. Throw an exception.
    Does your String in line 17 count as a number? I wouldn't start an integer with 0 myself.
    Change the end of line 22 to print

    Non-numeric text

    or

    Ordinary text

    ...or similar.

    There arre sites where you can find regexes to match numbers. Also look in the documentation for Scanner (I think), which shows which regex they use for numbers.
     
    Carey Brown
    Saloon Keeper
    Posts: 8578
    71
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Carey Brown wrote:Do you allow:....


    This is my big objection to resurrecting a 15 year old post. The original poster has graduated, married, and is raising a family, he's not around to say what the parameters of his usage were and Mark is making this up as he goes along without starting with a set of requirements that are more typical of a new post or be able to properly respond to this kind of question.
     
    Campbell Ritchie
    Marshal
    Posts: 74006
    332
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Carey Brown wrote:. . . a 15 year old post. The original poster[...]'s not around . . .

    I see the original replier is still around. If I remember correctly, that was 13th October, when the person who posted the first reply signed up
     
    Mike Simmons
    Master Rancher
    Posts: 4027
    53
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Yeah, that guy keeps hanging around. ;)
     
    Carey Brown
    Saloon Keeper
    Posts: 8578
    71
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Bob Robertson hasn't posted anything in the last 14 years.
     
    You showed up just in time for the waffles! And this tiny ad:
    Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    reply
      Bookmark Topic Watch Topic
    • New Topic