I am trying to loop through a string and check each character if one of the characters is a number. If it is a number, I want to return it as true. I have a string \"crash\"
Your code should work correctly, although I would probably use this instead:
public boolean isNumber(String newString)
{
for (int i=0; i != newString.length(); i++)
{
if (!Character.isDigit(newString.charAt(i)))
{
return false;
}
}
return true;
}
// a regex equivalent
public boolean isNumberRegex(String newString)
{
return newString.match("\\d+");
}
The method above checks if all characters are digits.
If I misunderstood your question and you want to check if any of the characters is a digit:
public boolean hasNumber(String newString)
{
for (int i=0; i != newString.length(); i++)
{
if (Character.isDigit(newString.charAt(i)))
{
return true;
}
}
return false;
}
// regex equivalent
public boolean hasNumberRegex(String newString)
{
return newString.match(".*\\d.*");
}