Java boolean method, for loop not returning proper true or false [closed]

public static boolean oneNumeric(String s) {
    String[] digit = {"0","1", "2", "3", "4", "5", "6" ,"7", "8", "9"};
    boolean numeric = true;
    for (int i=0; i< s.length(); i++) {
        if(!(s.contains(digit[i]))) {
                return false;
    }}
    return numeric;

}

I want to return true or false into my main method, but it won’t work in the for loop. I’m confused.

What am I doing wrong?

Answer

To make your method right, you should

  • remove useless numeric variable
  • use digit.length as upper bound, as you access the digit array
  • remove the ! and return true

It’ll will check, for each digit, if it is present in the string, if no one is in the string, return false

public static boolean oneNumeric(String s) {
    String[] digit = {"0","1", "2", "3", "4", "5", "6" ,"7", "8", "9"};
    for (int i=0; i< digit.length; i++) {
        if(s.contains(digit[i])) {
                return true;
        }
    }
    return false;    
}

But an easier method would be :

public static boolean oneNumeric(String s) {
    return s.matches(".*\d.*");              //  'd' is for digit in regex 
}

Leave a Reply

Your email address will not be published. Required fields are marked *