Iterating over a String to check for a number and printing out the String value if it doesn't have a number

Posted by wheelerlc64 on Stack Overflow See other posts from Stack Overflow or by wheelerlc64
Published on 2014-06-03T15:15:39Z Indexed on 2014/06/03 15:25 UTC
Read the original article Hit count: 120

Filed under:

I have set up my function for checking for a number in a String, and printing out that String if it has no numbers, and putting up an error message if it does. Here is my code:

public class NumberFunction 
{
    public boolean containsNbr(String str)
    {
        boolean containsNbr = false;
        if(str != null && !str.isEmpty())
        {
            for(char c : str.toCharArray())
            {
                if(containsNbr = Character.isDigit(c))
                {
                    System.out.println("Can't contain numbers in the word.");
                    break;
                }
                else
                {
                    System.out.println(str);
                }
            }
        }
        return containsNbr;
    }
}



import com.imports.validationexample.function.NumberFunction;

public class Main 
{
    public static void main(String[] args) 
    {
        NumberFunction nf = new NumberFunction();
        System.out.println(nf.containsNbr("bill4"));
    }
}

I am trying to get it to print out the result to the console, but the result keeps printing multiple times and prints the boolean value, which I do not want, something like this:

bill4
bill4
bill4
bill4
Can't contain numbers in the word.
true


Why is this happening? I've tried casting but that hasn't worked out either. Any help would be much appreciated.

© Stack Overflow or respective owner

Related posts about java