繁体   English   中英

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

[英]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;

我想从.txt文件中读取一组单词,并让程序选择一个在hangman游戏中使用的随机单词。

下面的代码用于当我们在代码中读取.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());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM