简体   繁体   中英

If Statement to detect certain words in a string

I'm trying to write a java program that detects specific words in a string, deemed "profane words". The user enters a string and the program should print to screen that profane words were detected for it should print that no profane words are detected. For this program the profane words are "cat", "dog", and "llama". The program should detect these words if they are capitalized. It should not identify words as profane that include the profane words. Ex: cats or catatonic are not profane.

I've written a program that runs and detects the profane words accordingly. However, it prints to the screen both "Profane word(s) detected" and "No profane words detected". I'm struggling to figure out how to just get it to print profane words detected when their is in fact a profane word.

import java.util.Scanner;

public class Ch3_Programming_Project3 {

    public static void main(String[] args) {

        Scanner keyboard=new Scanner(System.in);

        boolean startProgram=true; 

        System.out.println("The words cat, dog, and llama are considered"
                  +" profane and will not be allowed.");

        if (startProgram== true) {

            System.out.println("Please enter a sentence:");
            String sentence=keyboard.next();
            sentence=sentence.toLowerCase();

            boolean cat=true, dog=true, llama=true;

            if (sentence.contains("cat")) {
                cat=true;
            }

            if (sentence.contains("dog")) {
                dog=true;
            }

            if (sentence.contains("llama")) {
                llama=true;
            } else {
                System.out.println("No profanity detected." + " Sentence approved.");
            }

            if (cat==true || dog==true || llama==true) {

                if (cat == true) {
                    if (cat==true&&dog==true&&llama==true) {
                        System.out.println("Profanity detected");
                        System.exit(0);
                    } else if (cat==true && dog==true) {
                        System.out.println("Profanity detected");
                        System.exit(0);
                    } else if (cat==true && llama==true) {
                        System.out.println("Profanity detected");
                        System.exit(0);
                    } else {
                        System.out.println("Profanity detected");
                        System.exit(0);
                    }    
                }

                if (dog == true) {
                    if (dog==true && llama==true) {
                        System.out.println("Profanity detected");
                        System.exit(0);
                    } else {
                        System.out.println("Profanity detected");
                        System.exit(0);
                    }                     
                }

                if (llama == true) {
                    System.out.println("Profanity detected");
                    System.exit(0);
                }
            }
        } else if (startProgram == false) {
            System.exit(0);
        } else {
            System.out.println("Program was force closed.");
            System.exit(0);
        }
        System.exit(0);
    }//end main
}//end class

I am very new to java and genuinely want to learn. Yes, this is a homework assignment. But I have already submitted it and am here in an attempt to understand where my mistake is and learn. I've tried googling and searching other posts to identify my problem but have had no success.

Thank you in advance to anyone who can help me.

You code can be simplified a lot by splitting the sentence and storing the bad words in a List

    List<String> pwords = Arrays.asList(new String []{"dog", "cat", "llama"});

    String str = "it is raining a cat and a dog";
    // or accept from keyBoard
    //System.out.println("Please enter a sentence:");
    // String str = keyboard.nextLine();
    // str = str.toLowerCase();

    System.out.println(str);
    String [] arr = str.split("\\s+");
    for (String w : arr) {

        if (pwords.contains(w)) {
            System.out.println("contains profanity");
            return;
        }
    }
    System.out.println("a clean sentence");

edit

Output

it is raining a cat and a dog
contains profanity

it is raining a cats and a dogs
a clean sentence

Your program is overly complicated and can be simplified quite a bit.

First of all, all of your if/else statements can be reduced down to just one. Also, as Scary Wombat pointed out in the comments, you should have used keyboard.nextLine() to get the input from the user.

Here's the new code for you Main method:

public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);

    System.out.println("The words cat, dog, and llama are considered"
            + " profane and will not be allowed.");

    System.out.println("Please enter a sentence:");
    String sentence = keyboard.nextLine();
    sentence = sentence.toLowerCase();

    boolean foundProfane = false;
    if (sentence.matches(".*\\bcat\\b.*")
            || sentence.matches(".*\\bdog\\b.*")
            || sentence.matches(".*\\bllama\\b.*")) {
        foundProfane = true;
    }

    if (foundProfane) {
        System.out.println("Profanity Detected!");
    } else {
        System.out.println("No profanity detected!");
    }

}

The .*\\\\b and \\\\b.* in the strings allow you to capture only the full word, so it will not be flagged when entering "catalog," for example.

With using just one boolean to track whether a profane word was added, you can keep all of your checks in one place and just flip the boolean if a naughty word is found.

Also, I removed the whole startProgram structure, as it had no effect on the program at all.

Note: There are several other improvements that could be made but since you are just getting started with Java, this should still be in line with your current skill level. Happy Coding!

So you start the program by checking to see if a String contains the profane words and then have flags to indicate if it contains any profane words. Good approach.

However after this..

If any of the three flags are true: System.out.println("Profanity detected"); System.exit(0); System.out.println("Profanity detected"); System.exit(0);

If dog is true: System.out.println("Profanity detected"); System.exit(0); System.out.println("Profanity detected"); System.exit(0);

If either of the two flags are true: System.out.println("Profanity detected"); System.exit(0); System.out.println("Profanity detected"); System.exit(0);

Else: System.out.println("Profanity detected"); System.exit(0); System.out.println("Profanity detected"); System.exit(0);

if cat is true: System.out.println("Profanity detected"); System.exit(0); System.out.println("Profanity detected"); System.exit(0);

If either of the other two flags is true: System.out.println("Profanity detected"); System.exit(0); System.out.println("Profanity detected"); System.exit(0);

I'm going to stop there but I think you see my point. Basically every single branch in your if-else web here leads to the same thing. You need to consolidate it. You could simply do in your first if-else branch something like:

if(sentence.contains("llama") {
   System.out.println("Contains profane word: llama");
}
//And so on

This way you wouldn't even need flags or any other if-else 's (Also as pointed out in the other answers you need to change keyboard.next() to keyboard.nextLine()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM