0

I'm making a basic hangman program in java. I have a WORDS String that's an array. Simple. I wanted to replace that WORDS array with a .txt file.

    public static String readFileAsString(String fileName) {
        try {
          text = new String(Files.readAllBytes(Paths.get("/Users/veronica/Documents/Alex/Projects/java/projects/user-hangman/src/words.txt")));
        } catch (IOException e) {
          e.printStackTrace();
        }
        return text;
    }

The file contains plain words, for example:

a
ability
able

When I try to use it in my hangman program, the game goes like this: it selects a random word from the .txt file and prints it in System.out. But since, the file is just a simple .txt file with plain words, the game thinks that the whole .txt file is one String. How could I make each individual word in some sort of String for itself and make it work on my current program?

  • 1
    https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllLines-java.nio.file.Path- – JB Nizet Dec 21 '19 at 16:51
  • If words are on separate lines use `Files.readAllLines()` otherwise simply split on space char. – John Stringer Dec 21 '19 at 16:52
  • (1) Collect all lines as separate strings (2) pick random element from that collection. See duplicates for code example (they are at top of your question, you may need to refresh this page to see them). – Pshemo Dec 21 '19 at 16:59
  • This would solve your problem: https://stackoverflow.com/questions/34261466/how-to-extract-only-words-from-a-txt-file-in-java –  Dec 21 '19 at 17:00

0 Answers0