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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Java boolean method, for loop not returning proper true or false [closed] without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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 
}
We are here to answer your question about Java boolean method, for loop not returning proper true or false [closed] - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji