detect numeric value w/o regular expression

U

usgog

I have a string input, which might be a numeric value. So I want to
return false if it is a numeric value. What is the best and simplest
way to do that without using regular expression or import other
libraries? Because I don't want to load all the references. So
something like charAt and foreach to detect a char in the string?
 
H

hiwa

I have a string input, which might be a numeric value. So I want to
return false if it is a numeric value. What is the best and simplest
way to do that without using regular expression or import other
libraries? Because I don't want to load all the references. So
something like charAt and foreach to detect a char in the string?
You could use Character.isDigit() method if the string consists of
0-9 only.
 
L

Luc The Perverse

I have a string input, which might be a numeric value. So I want to
return false if it is a numeric value. What is the best and simplest
way to do that without using regular expression or import other
libraries? Because I don't want to load all the references. So
something like charAt and foreach to detect a char in the string?

You are not adding to the bulk of your program by using imported libraries.

Regardless

boolean isNumeric(String x){
for(char c : x.toCharArray())
if(c<'0||c>'9')
return false;
return true;
}

If you need it to work with negatives or decimal points it will require a
little extra work - not too much.
 
A

Andrew Thompson

I have a string input, which might be a numeric value. So I want to
return false if it is a numeric value. What is the best and simplest
way to do that without using regular expression or import other
libraries? Because I don't want to load all the references.

I don't think it will take long, for java.lang
classes (though any try/catch could add a
wallop of processing time).

<sscce>
class TestNumeric {
public static void main(String[] args) {
String input = "1.23";
Float f = new Float(input);
System.out.println(f);

input = "1.23f";
f = new Float(input);
System.out.println(f);

input = "1.23e7";
f = new Float(input);
System.out.println(f);

input = "f1.23";
f = new Float(input);
System.out.println(f);
}
}
</sscce>

<output>
1.23
1.23
1.23E7
Exception in thread "main" java.lang.NumberFormatException:
For input string: "f1.23"
....
</output>

Andrew T.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top