Why does my program not detect numbers 11 and 12?

public class SentenceValidator {

public static void main(String[] args) {

    String[] sentences = {
            "These sentences are valid.",
            "The quick brown fox said “hello Mr lazy dog”.",
            "The quick brown fox said hello Mr lazy dog.",
            "One lazy dog is too few, 13 is too many.",
            "One lazy dog is too few, thirteen is too many.",
            "How many \"lazy dogs\" are there?",
            "\n",
            "These sentences are invalid",
            "The quick brown fox said \"hello Mr. lazy dog\".",
            "the quick brown fox said “hello Mr lazy dog\".",
            "\"The quick brown fox said “hello Mr lazy dog.\"",
            "One lazy dog is too few, 12 is too many.",
            "Are there 11, 12, or 13 lazy dogs?",
            "There is no punctuation in this sentence"
    };

    for (String sentence : sentences) {
        System.out.println(String.format("\"%s\" is a valid sentence: %s", sentence, isValidSentence(sentence)));
    }
}

public static boolean isValidSentence(String str) {
    // Check if string starts with a capital letter
    if (!Character.isUpperCase(str.charAt(0))) {
        return false;
    }

    // Check if numbers below 13 are spelled out
    String[] words = str.split(" ");
    for (String word : words) {
        if (word.matches("^[0-9]+$")) { // Check if word is a number
            int num = Integer.parseInt(word);
            if (num > 0 && num < 13) {
                return false;
            }
        }
    }

    // If all checks pass, return true
    return true;
}

}

The sentence "Are there 11, 12, or 13 lazy dogs?" returns true where it should return false as the numbers 11 and 12 are present however it does not seem to detect them? what have i done incorrectly

>Solution :

You need to remove the commas before splitting the string into words, because you are later parsing them as Integers and your regex will not match. It will work if you change the line

String[] words = str.split(" ");

to

String[] words = str.replace(",", "").split(" ");

Leave a Reply