sarahjane sarahjane - 7 months ago 4
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( System.in);
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.

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

Answer

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

    try 
    {
        Scanner input = new Scanner(System.in);
        File file = new File("ComputerText.txt");

        input = new Scanner(file);

        String contents;
        while (input.hasNext()) 
        {
            contents = input.next();
        }
        input.close();

    } 
    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

Comments