Search code examples
javadigits

program to find if two characters in String in a row are digits does not work in java


I have the code below, which I want to take input from the keyboard and show me if the input contains 2 digits in a row. If so, I want to get false printed out in the console, otherwise true. It works fine, except when the first 2 characters of the input are digits. In that case, I still get true in the console. Can anyone understand why? Thanks in advance

import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System. in );
        System.out.println("Enter:");
        String s = sc.nextLine();
        if (checkDigit(s)) {
            System.out.println("false");
        } else {
            System.out.println("true");
        }
    }
    public static boolean checkDigit(String s) {
        boolean b = true;
        char[] c = s.toCharArray();
        for (int i = 0; i < c.length - 1; i++) {
            if (Character.isDigit(c[i]) && Character.isDigit(c[i + 1])) {
                b = true;
            } else {
                b = false;
            }
        }
        return b;
    }
}

Solution

  • You continue to check the input string even when you already found the result. As noted by @Stultuske, you overwrite the value of the variable b, so your code will only return true, if the last two chars are digits.

    You would need to return from the loop if there are two digits in a row:

     public static boolean checkDigit(String s) {
        char[] c = s.toCharArray();
    
        for(int i=0; i < c.length-1; i++) {
            if(Character.isDigit(c[i]) && Character.isDigit(c[i+1])) {
                return true;
            }
        }
    
        return false;
     }
    

    UPDATE: in fact there was an error in the snippet, as it was returning too early from the loop. Fixed now.