Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Help with the extra credit in teachers notes from 'Censoring Words' Java basics video .contains() method

Trying to check to see if one string is contained within the other using .contains() method i.e if "Tree" appears in "Treehouse" without storing Treehouse as "Tree", 'House" but code below will only match on exact word. User prompt adds 'noob' code skips the if block, user prompt adds 'dorkjerknerdnoob' if block is called.

Thanks in advance, I cant see where its wrong?

            String noun;
            String badWords = "dorkjerknerdnoob";
            boolean isInvalidWord;

            do {
                noun = console.readLine("What's your noun? \n");
                isInvalidWord = noun.toLowerCase().contains(badWords);
                if (isInvalidWord) {
                    console.printf("That language is not allowed! Try again \n\n");
                };
            } while (isInvalidWord);

4 Answers

In my head it should be an imported list of some sort, surely people are not adding 1000 words+ to their code for scenarios like this?

You're right, that would be horrible, usually it is read from a file. The data that your program usually gets from a database or just from a file on your pc is in JSON(which I think you are farmiliar with).

So in case of your code, the JSON could be something like:

Suppose this is data.json

{"badWords" : ["dork", "jerk", "nerd", "noob"]}

You can read the data stored in it with the following code:

    public static void main(String[] args) throws Exception {
//read the file
        FileReader fr = new FileReader("data.json");
        Scanner sc = new Scanner(fr);
//store the data as a string inside of jsonAsString
        String jsonAsString = "";
        while(sc.hasNext()){
            jsonAsString += sc.next();
        }

//read the data as a JSON object
        JSONObject obj = new JSONObject(jsonAsString);

//gets the array within the JSON object with the key "badWords"
        JSONArray badWords = obj.getJSONArray("badWords");

//prints out all the bad words: 
        for(int i = 0; i < badWords.length(); i++){
            System.out.println(badWords.get(i));
        }

/* Output:
dork
jerk
nerd
noob
*/
    }

You probably won't understand all of this, but hopefully it gives you a feel for how it goes. Usually though the JSON would be requested from a server which which sends so you a similar JSON file, the data originates from the database.

is it normal practice to let arrays get that large?

An array in java can store up to: 2147483648 elements. In most situations though, you will not be able to entirely fill an array to have this many elements without getting Heap or memory overflow. In case you absolutely need all of that data in memory your probably going to have to increase your max size for the Heap through terminal. And if you set max-size to the maximum value which your computer supports and it still isn't enough, then you're going to need to rethink your approach and come up with a differnt solution to achieve the same thing, but not load the entire data set to the memory.

Great Post

Hi Neil,

Here's what you need to do:

                isInvalidWord = badWords.contains(noun.toLowerCase());

We check badwords for whether it contains the noun(lowercased). In your code it was the other way around. So it checked whether the noun conained dorkjerknerdnoob, which of course is not true.

And by the way, the method your using isn't recommended. I would rather create an array with all the bad words inside of it, and create a function which loops through it and checks whether the noun entered is within this list. This is better because your list of bad words will be a lot more readable and easier to adjust and as a bonus, you won't make mistakes like this so easily, because it is much more clear what your dealing with!

It's worth noting that at the point in the course where this challenge is given they have not covered arrays, and not any loop type other than do/while loops. That's likely why Neill dev's code is written somewhat inefficiently.

In fact (at least when I went through the Java course) for loops (which would work best here) were not covered in the main track at all. It was only covered in the Feeling Loopy with Java workshop. If that is still the case then I definitively recommend that Neil goes though that workspace.

Then Neill dev should definitely follow that workshop :)

Haha! thats great thanks for the speedy response both and yes..makes perfect sense now! I've seen the method working in Jshell but as it was the extra credit part of the course I was concentrating on the method more than thinking about the code as a whole..a valuable lesson l feel.

Appreciate the tip to make the code more efficient. I was considering how that would be managed in the real world. In my head it should be an imported list of some sort, surely people are not adding 1000 words+ to their code for scenarios like this? or is it dealt with in a different way altogether? is it normal practice to let arrays get that large?

Kind regards Neill

Fantastic, thanks for taking the time to put together such a comprehensive answer. I can follow the syntax above and it makes sense but could not replicate it at this stage unless following a video. It is a good insight though, I assume this would be linked directly or in some way to the phrase 'Memory leak' which has always puzzled me. Ive had memory issues before with Virtual machines when playing around with GUI automated testing for a Java application but thats really the only exposure I've had to that side of things. It will come i'm sure, I am redoing this Java course and it's definitely the most productive time I've spent with the language for both understanding and retaining the information.

Genuine thanks First Last and I hope to speak with you in the future.

Kind regards Neill