sarahjane sarahjane - 1 year ago 38
Java Question

How do I get my Hangman Java file to read a random word in from a .txt file?

char hangman[];
Scanner sc = new Scanner(;
Random r = new Random();
File input = new File("ComputerText.txt").useDelimiter(",");
Scanner sc = new Scanner(input);
String words;

I want to read in a set of words from a .txt file and have the program select a random word to use in the hangman game.

The below code is for when we get the .txt file to be read inside the code.
We want to use three different .txt files with a different category each and have the user pick which category they want their word from.

if ( decision == 1)
else if ( decision == 2)
word = countryWord;
else if (decision == 3)
word = fruitWord;
System.out.println("error, try again");

Answer Source

Here is how a file must be read with the scanner class :-

        Scanner input = new Scanner(;
        File file = new File("ComputerText.txt");

        input = new Scanner(file);

        String contents;
        while (input.hasNext()) 
            contents =;

    catch (Exception ex) 

at this point all the file contents will be in the contetns variable, you can then use the split method to split according to your delimeter