如何让我的Hangman Java文件从.txt文件中读取随机单词?

时间:2016-04-14 15:41:42

标签: java file if-statement random

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;

我想从.txt文件中读取一组单词并让程序选择一个随机单词用于刽子手游戏。

以下代码适用于我们在代码中读取.txt文件的时间。 我们希望使用三个不同的.txt文件,每个文件具有不同的类别,并让用户选择他们想要的类别。

//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");
}

2 个答案:

答案 0 :(得分:0)

以下是扫描仪类必须读取文件的方法: -

    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) 
    {
    }

此时所有文件内容都将在contetns变量中,然后您可以根据您的分隔符使用split方法进行拆分

答案 1 :(得分:0)

你的方法应该是:

使用以下导入:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

创建返回所需单词的函数:

if ( decision == 1)
{
    word = getComputerWord();
}
else if ( decision == 2)
{
    word = getCountryWord();
}
else if (decision == 3)
{
    word = getFruitWord();
}
else
{
    System.out.println("error, try again");
}

以下列方式实施:

public String getComputerWord() {
    return getRandomWordFromFile(computerWordsPath);
}

public String getCountryWord() {
    return getRandomWordFromFile(countryWordsPath);
}

public String getFruitWord() {
    return getRandomWordFromFile(fruitWordsPath);
}

//returns random word from ","-delimited file of words
public String getRandomWordFromFile(String path) {
    String fileContent = readFileToString(path);
    String[] words = fileContent.split(",");
    Random rng = new Random();
    return words[rng.nextInt() % words.length];
}


//build string from file by simply concatenating the lines
public String readFileToString(String path) {
    try { 
        BufferedReader br = new BufferedReader(new FileReader(path));

        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                line = br.readLine();
            }
            return sb.toString();
        } finally {
            br.close();
        }
    } catch (IOException ioe) {
        //Error handling of malformed path
        System.out.println(ioe.getMessage());
    }
}