My assaigment was:

Suppose we are working for an online service that provides a bulletin board for its users. We would like to give our users the option of filtering out profanity. Suppose we consider the words cat, dog and llama to be profane. Write a program that reads a string from the keyboard and tests whether the string contains one or more of our profane words. Your program should find words like cAt that differ only in case. Your program should display the read string with the profanities replaced with the character '*'.

Your program should modify lines that contain profanities only, not lines that contain words like, dogmatic or concatenate or category.

This is what I have so far,

import java.util.Scanner;

public class SomeClass 
{
public static void main(String [] args){

    String name;
    int case_num = 0;

    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter sentences");
    name = keyboard.next();
    name.equalsIgnoreCase(name);


    if (name.contains("cat "))//(name.indexOf("cat") !=-1) //testing if the "" (Space) will read 'cat' only and not 'cattt' 
    {

        case_num = 1;

    }

    else if (name.indexOf("dog") !=-1)
    {

        case_num = 1;

    }

    else if (name.indexOf("llama") != -1)
    {
        //System.out.println("Profanity found");
        case_num = 1;
    }

    switch(case_num)
    {
    case 1:

        System.out.println("Profanity found");
        break;

    default:
        System.out.println("no found");
    }


  }

}

The problem is that it's not doing what the assaigment is asking for =(
If i type 'cat' it says (no found) and I believe it should say (profainy found)
I think I'm missing something, but I don't know what is it.

Edited 3 Years Ago by iTechnnn

You are looking for "cat ", so if the input is "cat" it won't match.
Anyway, your algorithm would also find "muscat ", so it's not perfect.

You are using Scanner's next() method - what happens if the input is more than one word?

Line 11 doesn't do anything (more precisely it always returns true, then throws that result away)

Use nextLine (as intimated by James in his first post) and, unless you are not allowed to as part of this assignment, use replaceAll and some regex (keyword word boundary).

This article has been dead for over six months. Start a new discussion instead.