首页 > 解决方案 > 从文件中读取一个随机单词供用户猜测 - Java

问题描述

我正在编写一个从文件中提取一个单词并猜测它的代码。例如,这个词是“苹果”。

用户将看到: *****

如果他们输入“p”作为猜测,他们会看到:*pp**

到目前为止,如果我在一个名为 secretPhrase 的变量中手动输入单词 apple,它就可以工作,但是我不确定如何让程序从文本文件中提取单词并将其存储到 secretPhrase 中以供用户猜测。

public static void main(String args[]) {
    String secretPhrase = "apple";
    String guesses = " ";
    Scanner keyboard = new Scanner(System.in);
    boolean notDone = true;

    Scanner word = new Scanner(System.in);

    System.out.print("Enter a word: ");



    while(true) {

        notDone = false;
        for(char secretLetter : secretPhrase.toCharArray()) { 
            if(guesses.indexOf(secretLetter) == -1) { 
                System.out.print('*');
                notDone = true;
            } else {
                System.out.print(secretLetter);
            }
        }
        if(!notDone) {
            break;
        }

        System.out.print("\nEnter your letter:");
        String letter = keyboard.next();
        guesses += letter;
    }
    System.out.println("Congrats");
}

标签: java

解决方案


你有几个选择。一是做到以下几点。它不完整,不检查边境案件。但你可以弄清楚。它假定文件每行包含一个单词。

        try {
            RandomAccessFile raf = new RandomAccessFile(
                    new File("wordfile.txt"), "r");
            Random r = new Random();
            // ensure the length is an int
            int len = (int)(raf.length()&0x7FFFFFFF);
            // randomly select a location
            long loc = r.nextInt(len);
            // go to that file location
            raf.seek(loc);
            // find start of next line
            byte c = raf.readByte();
            while((char)c != '\n') {
                c = raf.readByte();
            }
            // read the line
            String line = raf.readLine();
            System.out.println(line);
        } catch (Exception e) {
            e.printStackTrace();
        }   
    }

对于一组较小的单词,一个更简单的解决方案是将它们读入 aList<String>并执行 aCollections.shuffle()以随机化它们。然后按打乱顺序使用它们。


推荐阅读