Reputation: 677
I'm trying to write a method that checks if a string has only numbers in it. For some reason it returns false even if I input a string containing "1234". I'm guessing my problem is with the if statement, but I'm not sure what to do to fix it.
public static boolean isNumeric(String input)
{
input.trim();
for (int count=0; count<=input.length(); count++)
{
if (input.substring(count) == "0" || input.substring(count) == "1"||
input.substring(count) == "2" || input.substring(count) == "3" ||
input.substring(count) == "4" || input.substring(count) == "5" ||
input.substring(count) == "6" || input.substring(count) == "7" ||
input.substring(count) == "8" || input.substring(count) == "9")
{
integerstate = true;
}
else
{
integerstate = false;
break;
}
}
return integerstate;
}
Does anyone see what the problem is?
Upvotes: 0
Views: 1030
Reputation: 3889
The cause behind this is difference between == and equals().
This happen because == compare for exact equality means two object must be same. while equal() compare for meaningful equality means object may not me same but the value they contain are meaningfully same.
Upvotes: 0
Reputation: 21
public static boolean isNumeric(String input) {
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(input);
if (isNum.matches()) {
return true;
}
return false;
}
Upvotes: 2
Reputation: 168835
You might let the tool-kit do the 'heavy lifting'.
class TestForIntegers {
public static void main(String[] args) {
String s = "blah";
System.out.println(s + " is integer: " + isInteger(s));
s = "1234";
System.out.println(s + " is integer: " + isInteger(s));
s = "max123";
System.out.println(s + " is integer: " + isInteger(s));
}
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
return true;
} catch (Exception e) {
return false;
}
}
}
blah is integer: false
1234 is integer: true
max123 is integer: false
Press any key to continue . . .
Upvotes: 1
Reputation: 81724
@Kal's answer is literally correct, but my goodness, @Petefic, this is a horribly inefficient way to do things. There's a method in the Character
class that checks if a char
is a digit, and you could just extract each character once instead of calling substring()
so many times.
For instance, you might do
public static boolean isNumeric(String input) {
input = input.trim();
for (char c: input.toCharArray()) {
if (Character.isDigit(c))
return true;
}
return false;
}
For the number 99999
, your code would produce over 50 new objects; this would produce one (the array from toCharArray()
.)
I see a few other answers that suggest using Integer.parseInt()
and catching the exception. That's not a terrible idea, but it's actually not a great one if many of the strings will not be numbers. Throwing and catching an exception is very computationally expensive; many objects are created in the process. It should be avoided in cases where actual error recovery is not involved.
Upvotes: 5
Reputation: 2679
Like Kal said, the == operator is determining whether the objects are the same object, not if they have the same value. With Java, this will often get you the same result, which can make it more difficult to realize why using == to compare strings is wrong. It will sometimes work because Java interns Strings with a String pool, which means Java will generally only store one String of each value. In other words, if String x and String y both have the value of "asdf", the String pool will only store "asdf" once and both x and y will reference that String object. The only way to force Java to actually create a duplicate String object is with the "new" keyword. I think in this case, == is not working due to the substring. In any case, unless you're actually checking to see if the objects being referenced are the same, always use .equals().
Upvotes: 1
Reputation: 121799
// Bad
for (int count=0; count<=input.length(); count++)
{
if (input.substring(count) == "0" || input.substring(count) == "1"||
input.substring(count) == "2" || input.substring(count) == "3" ||
input.substring(count) == "4" || input.substring(count) == "5" ||
input.substring(count) == "6" || input.substring(count) == "7" ||
input.substring(count) == "8" || input.substring(count) == "9")
{
integerstate = true;
...
// Better
for (int count=0; count<=input.length(); count++)
{
if (input.substring(count).equals("0") || ...
...
// Much better
try {
Integer.parseInt( input );
integerstate = true;
}
catch ...
Upvotes: 0
Reputation: 2496
In java to check for equality of two strings or comparing them you need to use the equals() since equals() does the content comparison. But '==' does the reference comparison so it just checks if the two references on both side of '==' are pointing to same object or not.
Upvotes: 0
Reputation: 6817
Another option would be to use charAt() instead of substring and compare against '0', '1' etc. Then you can use ==. A far more efficient way however would be to use regular expressions.
Upvotes: 1
Reputation: 15052
You should use the equals
method for String
equality.
And if you want to use it the other way around,consider converting your substrings
using Integer.parseInt()
and then you can use == 0
.
Upvotes: 0