Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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(" ");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading