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


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

以下是必须使用扫描程序类读取文件的方式:-

    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 方法根据您的分量仪进行拆分

你的方法应该是:

具有以下导入:

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());
    }
}

最新更新