• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to check if String() value is numeric

 
Bartender
Posts: 10780
71
  • Number of slices to send:
    Optional 'thank-you' note:

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: 79392
377
  • Number of slices to send:
    Optional 'thank-you' note:
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
  • Number of slices to send:
    Optional 'thank-you' note:
iterate the string using charAt(index) and for each char ch:
Character.isDigit(ch)
 
Master Rancher
Posts: 4905
74
  • Number of slices to send:
    Optional 'thank-you' note:

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
  • Number of slices to send:
    Optional 'thank-you' note:
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: 4905
74
  • Number of slices to send:
    Optional 'thank-you' note:
Really? Why is that?
 
Greenhorn
Posts: 6
  • Number of slices to send:
    Optional 'thank-you' note:
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: 4905
74
  • Number of slices to send:
    Optional 'thank-you' note:
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: 79392
377
  • Number of slices to send:
    Optional 'thank-you' note:
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: 4905
74
  • Number of slices to send:
    Optional 'thank-you' note:
Well, I was referring more to the fact that the inequalities are completely backwards.
 
Campbell Ritchie
Marshal
Posts: 79392
377
  • Number of slices to send:
    Optional 'thank-you' note:
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: 4905
74
  • Number of slices to send:
    Optional 'thank-you' note:
Yeah, this code has many problems.

In comparison, Character.isDigit() simply works.
 
Campbell Ritchie
Marshal
Posts: 79392
377
  • Number of slices to send:
    Optional 'thank-you' note:

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!
 
Marshal
Posts: 28258
95
  • Number of slices to send:
    Optional 'thank-you' note:

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
  • Number of slices to send:
    Optional 'thank-you' note:
Regular expressions is your answer
 
Greenhorn
Posts: 9
  • Number of slices to send:
    Optional 'thank-you' note:
you can use regular expression.[0-9]
 
imed joseph
Greenhorn
Posts: 9
  • Number of slices to send:
    Optional 'thank-you' note:

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: 79392
377
  • Number of slices to send:
    Optional 'thank-you' note:
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
  • Number of slices to send:
    Optional 'thank-you' note:
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: 79392
377
  • Number of slices to send:
    Optional 'thank-you' note:
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
  • Number of slices to send:
    Optional 'thank-you' note:
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: 79392
377
  • Number of slices to send:
    Optional 'thank-you' note:

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
  • Number of slices to send:
    Optional 'thank-you' note:
Hi! Mr. Ritchie how about the following code? What do you think? Please feel free to let me know.



 
Saloon Keeper
Posts: 10779
86
  • Number of slices to send:
    Optional 'thank-you' note:
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: 79392
    377
    • Number of slices to send:
      Optional 'thank-you' note:
    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: 10779
    86
    • Number of slices to send:
      Optional 'thank-you' note:

    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: 79392
    377
    • Number of slices to send:
      Optional 'thank-you' note:

    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: 4905
    74
    • Number of slices to send:
      Optional 'thank-you' note:
    Yeah, that guy keeps hanging around. ;)
     
    Carey Brown
    Saloon Keeper
    Posts: 10779
    86
    • Number of slices to send:
      Optional 'thank-you' note:
    Bob Robertson hasn't posted anything in the last 14 years.
     
    Consider Paul's rocket mass heater.
    reply
      Bookmark Topic Watch Topic
    • New Topic
    vceplus-200-125    | boson-200-125    | training-cissp    | actualtests-cissp    | techexams-cissp    | gratisexams-300-075    | pearsonitcertification-210-260    | examsboost-210-260    | examsforall-210-260    | dumps4free-210-260    | reddit-210-260    | cisexams-352-001    | itexamfox-352-001    | passguaranteed-352-001    | passeasily-352-001    | freeccnastudyguide-200-120    | gocertify-200-120    | passcerty-200-120    | certifyguide-70-980    | dumpscollection-70-980    | examcollection-70-534    | cbtnuggets-210-065    | examfiles-400-051    | passitdump-400-051    | pearsonitcertification-70-462    | anderseide-70-347    | thomas-70-533    | research-1V0-605    | topix-102-400    | certdepot-EX200    | pearsonit-640-916    | itproguru-70-533    | reddit-100-105    | channel9-70-346    | anderseide-70-346    | theiia-IIA-CIA-PART3    | certificationHP-hp0-s41    | pearsonitcertification-640-916    | anderMicrosoft-70-534    | cathMicrosoft-70-462    | examcollection-cca-500    | techexams-gcih    | mslearn-70-346    | measureup-70-486    | pass4sure-hp0-s41    | iiba-640-916    | itsecurity-sscp    | cbtnuggets-300-320    | blogged-70-486    | pass4sure-IIA-CIA-PART1    | cbtnuggets-100-101    | developerhandbook-70-486    | lpicisco-101    | mylearn-1V0-605    | tomsitpro-cism    | gnosis-101    | channel9Mic-70-534    | ipass-IIA-CIA-PART1    | forcerts-70-417    | tests-sy0-401    | ipasstheciaexam-IIA-CIA-PART3    | mostcisco-300-135    | buildazure-70-533    | cloudera-cca-500    | pdf4cert-2v0-621    | f5cisco-101    | gocertify-1z0-062    | quora-640-916    | micrcosoft-70-480    | brain2pass-70-417    | examcompass-sy0-401    | global-EX200    | iassc-ICGB    | vceplus-300-115    | quizlet-810-403    | cbtnuggets-70-697    | educationOracle-1Z0-434    | channel9-70-534    | officialcerts-400-051    | examsboost-IIA-CIA-PART1    | networktut-300-135    | teststarter-300-206    | pluralsight-70-486    | coding-70-486    | freeccna-100-101    | digitaltut-300-101    | iiba-CBAP    | virtuallymikebrown-640-916    | isaca-cism    | whizlabs-pmp    | techexams-70-980    | ciscopress-300-115    | techtarget-cism    | pearsonitcertification-300-070    | testking-2v0-621    | isacaNew-cism    | simplilearn-pmi-rmp    | simplilearn-pmp    | educationOracle-1z0-809    | education-1z0-809    | teachertube-1Z0-434    | villanovau-CBAP    | quora-300-206    | certifyguide-300-208    | cbtnuggets-100-105    | flydumps-70-417    | gratisexams-1V0-605    | ituonline-1z0-062    | techexams-cas-002    | simplilearn-70-534    | pluralsight-70-697    | theiia-IIA-CIA-PART1    | itexamtips-400-051    | pearsonitcertification-EX200    | pluralsight-70-480    | learn-hp0-s42    | giac-gpen    | mindhub-102-400    | coursesmsu-CBAP    | examsforall-2v0-621    | developerhandbook-70-487    | root-EX200    | coderanch-1z0-809    | getfreedumps-1z0-062    | comptia-cas-002    | quora-1z0-809    | boson-300-135    | killtest-2v0-621    | learncia-IIA-CIA-PART3    | computer-gcih    | universitycloudera-cca-500    | itexamrun-70-410    | certificationHPv2-hp0-s41    | certskills-100-105    | skipitnow-70-417    | gocertify-sy0-401    | prep4sure-70-417    | simplilearn-cisa    |
    http://www.pmsas.pr.gov.br/wp-content/    | http://www.pmsas.pr.gov.br/wp-content/    |