简体   繁体   English

从文本文件中选择一个随机词

[英]Choosing a Random word from a text file

I'm trying to develop a hangman as an assignment, and is unable to get one random word from a Text file(which has various words and each word is separated with a space).我正在尝试开发一个刽子手作为一项任务,并且无法从文本文件中获取一个随机单词(其中包含各种单词并且每个单词都用空格分隔)。 I've written a code to get a random word, but unable to pick one words and replace it, with the sample string (String w = "this";) i have in the "Function()".我编写了一个代码来获取一个随机单词,但无法选择一个单词并将其替换为我在“Function()”中的示例字符串 (String w = "this";)。

 public String randomWord(String wordran) {

    try {
        BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt"));
        String line = reader.readLine();
        List<String> words = new ArrayList<String>();
        while (line != null) {
            String[] wordline = line.split(" ");
            for (String word : wordline) {
                words.add(word);
            }
            Random rand = new Random();
            String randomWord1 = words.get(rand.nextInt(words.size()));
            //System.out.println("rand word : " + randomWord1);

        }
        reader.close();

    } catch (Exception e) {

    }
    return wordran;


}


   public void function(){

    int numGuesses = 10;
    String w = randomWord();

    String[] word = w.split("");
    ArrayList< String> wList = new ArrayList<>(Arrays.asList(word));
    ArrayList< String> wAnswer = new ArrayList< String>(wList.size());
    for (int i = 0; i < wList.size(); i++) {
        wAnswer.add("_ ");
    }
    int left = wList.size();
    Scanner scanner = new Scanner(System.in);
    boolean notDone = true;
    ArrayList< String> lettersGuessed = new ArrayList< String>();

    while (notDone) {
        System.out.println();
        String sOut = "";

        List< String> lettersLeft = getRemainingLetters(lettersGuessed);
        for (String s : lettersLeft) {
            sOut += s + " ";
        }
        System.out.println("Letters Left: " + sOut);

        sOut = "";
        for (int i = 0; i < wList.size(); i++) {
            sOut += wAnswer.get(i);
        }
        System.out.println(sOut + " Guesses left:" + numGuesses);
        System.out.print("Enter a letter(* exit): ");
        String sIn = scanner.next();
        numGuesses--;
        if (sIn.equals("*")) {
            break;
        }
        lettersGuessed.add(sIn);
        for (int i = 0; i < wList.size(); i++) {
            if (sIn.equals(wList.get(i))) {
                wAnswer.set(i, sIn);
                left--;
            }
        }
        if (left == 0) {
            System.out.println("Congradulations you guessed it!");
            break;
        }
        if (numGuesses == 0) {
            System.out.println("You failed...:(");
            break;
        }

    }

}

public static void main(String[] args) throws IOException {
    Main ma = new Main();

    ma.function();

    loadWords();

   // ma.randomWord();

}

There are three problems with your code:您的代码存在三个问题:

  1. You don't need to pass the parameter, String wordran to store the random word.您不需要传递参数String wordran来存储随机词。 A useful parameter can be String path through which you can pass the path of the file to the function.一个有用的参数可以是String path ,通过它您可以将文件的路径传递给 function。
  2. You've missed reading the content from the file in the loop.您错过了从循环中的文件中读取内容。 You've read just the first line.你已经阅读了第一行。
  3. You haven't returned the random word which you have calculated by applying Random#nextInt .您还没有返回通过应用Random#nextInt计算的随机词。

On a side note, I recommend you use try-with-resources syntax to get rid of closing BufferedReader explicitly.附带说明一下,我建议您使用try-with-resources语法来避免显式关闭BufferedReader

Given below is the correct code incorporating these comments:下面给出了包含这些注释的正确代码:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Main {
    public static void main(String[] args) throws IOException {
        // Test
        System.out.println(getRandomWord("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt"));
    }

    public static String getRandomWord(String path) throws IOException {
        List<String> words = new ArrayList<String>();
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] wordline = line.split("\\s+");
                for (String word : wordline) {
                    words.add(word);
                }
            }
        }
        Random rand = new Random();
        return words.get(rand.nextInt(words.size()));
    }
}

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

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