从文本文件中选择一个随机词 [英] Choosing a Random word from a text file

查看:138
本文介绍了从文本文件中选择一个随机词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试开发一个子手作为一项任务,并且无法从文本文件中获得一个随机单词(该单词有各种单词,每个单词都用空格分隔).我已经编写了一个代码以获取一个随机单词,但是无法选择一个单词并将其替换为示例字符串(String w ="this";),该字符串已包含在"Function()"中.

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()".

 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. 您不需要传递参数String wordran来存储随机单词.有用的参数可以是String path,通过它您可以将文件的路径传递给函数.
  2. 您错过了在循环中读取文件内容的操作.您只读了第一行.
  3. 您尚未返回通过应用Random#nextInt计算出的随机词.
  1. You don't need to pass the parameter, String wordran to store the random word. A useful parameter can be String path through which you can pass the path of the file to the 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.

另一方面,我建议您使用试试-资源语法来明确关闭BufferedReader.

On a side note, I recommend you use try-with-resources syntax to get rid of closing BufferedReader explicitly.

下面给出的是包含这些注释的正确代码:

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

这篇关于从文本文件中选择一个随机词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆