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

Why am I getting a NullPointerException when I use System.console().readLine()?

This is with regards to the "TreeStory" coding challenge in Java - local development environments.

package com.teamtreehouse;

import java.io.IOException; import java.util.Arrays; import java.util.List;

public class Main {

public static void main(String[] args) {
// write your code here
    // TODO:csd - Instantiate a new Prompter object and prompt for the story template
    Prompter prompter = new Prompter();
    List<String> results;
    String story = "Thanks __name__ for helping me out.  You are really a __adjective__ __noun__ and I owe you a __noun__.";
    Template tmpl = new Template(story);
    // TODO:csd - Use the prompter object to have it do the prompting, censoring and outputting.  Call Prompter.run
    prompter.run(tmpl);
    try {
        results = prompter.promptForWords(tmpl);
        String treeStory = tmpl.render(results);
        System.out.printf("Your TreeStory:%n%n%s", treeStory);
    } catch (IOException e) {
        e.printStackTrace();
    }
    // TODO:csd - This should really happen in the Prompter.run method, let's get these implementation details out of the main method

}

}

package com.teamtreehouse;

import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;

public class Template { /** * The string format that is waiting to receive values */ private String mCompiled; private List<String> mPlaceholders;

/**
 * @param text A template with double underscored surrounded placeholders. eg: Hello __name__!
 */
public Template(String text) {
    // Match on double underscore surrounded words, like __name__ or __proper noun__
    Pattern pattern = Pattern.compile("__([^__]+)__");
    Matcher matcher = pattern.matcher(text);
    mPlaceholders = new ArrayList<String>();
    while (matcher.find()) {
        String label = matcher.group(1);
        mPlaceholders.add(label);
    }
    mCompiled = matcher.replaceAll("%s");
}


/**
 * @return Ordered names of placeholders in the template
 */
public List<String> getPlaceHolders() {
    return mPlaceholders;
}


/**
 * Given a list of values, replaces the fill in the blanks in order.
 *
 * @param values The replacements for the fill in the blank
 * @return The filled out TreeStory
 */
public String render(List<String> values) {
    // String.format accepts the templates and Object... (a variable amount of objects)
    return String.format(mCompiled, values.toArray());
}

}

package com.teamtreehouse;

import java.io.*; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;

public class Prompter { private BufferedReader mReader; private Set<String> mCensoredWords;

public Prompter() {
    mReader = new BufferedReader(new InputStreamReader(System.in));
    loadCensoredWords();
}

private void loadCensoredWords() {
    mCensoredWords = new HashSet<String>();
    Path file = Paths.get("resources", "censored_words.txt");
    List<String> words = null;
    try {
        words = Files.readAllLines(file);
    } catch (IOException e) {
        System.out.println("Couldn't load censored words");
        e.printStackTrace();
    }
    mCensoredWords.addAll(words);
}

public void run(Template tmpl) {
    List<String> results = null;
    try {
        results = promptForWords(tmpl);
    } catch (IOException e) {
        System.out.println("There was a problem prompting for words");
        e.printStackTrace();
        System.exit(0);
    }
    // TODO:csd - Print out the results that were gathered here by rendering the template
    try {
        System.out.printf("%s", tmpl.render(promptForWords(tmpl)));
    } catch (IOException e) {
        e.printStackTrace();
    }

}

/**
 * Prompts user for each of the blanks
 *
 * @param tmpl The compiled template
 * @return
 * @throws IOException
 */
public List<String> promptForWords(Template tmpl) throws IOException {
    List<String> words = new ArrayList<String>();
    for (String phrase : tmpl.getPlaceHolders()) {
        String word = promptForWord(phrase);
        words.add(word);
    }
    return words;
}


/**
 * Prompts the user for the answer to the fill in the blank.  Value is guaranteed to be not in the censored words list.
 *
 * @param phrase The word that the user should be prompted.  eg: adjective, proper noun, name
 * @return What the user responded
 */

public String promptForWord(String phrase) throws IOException {
    // TODONE:csd - Prompt the user for the response to the phrase, make sure the word is censored, loop until you get a good response.
    System.out.printf("Please give me a %s", phrase);
    String word = System.console().readLine();
    boolean isBadWord = mCensoredWords.contains(word);
    do {
        if (isBadWord) {
            System.out.printf("The word, %s, is not allowed. Please try again with a different %s:  ", phrase);
            word = System.console().readLine();
        }
    } while(isBadWord);
    return word;
}

}