【问题标题】:Randomly choose a word from a text file从文本文件中随机选择一个单词
【发布时间】:2012-08-15 05:24:13
【问题描述】:

我正在尝试完成我的大学作业,但我在哪里可以找到从文本文件中读取并从列表中随机选择一个单词的方法!作业是关于刽子手的,程序假设从列表中选择一个随机单词

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

public class Hangman extends JFrame
{
int i = 0;
static JPanel panel;
static JPanel panel2;
static JPanel panel3;

public Hangman()
{
JButton[] buttons = new JButton[26];

panel = new JPanel(new GridLayout(0,9));
panel2 = new JPanel();
panel3 = new JPanel();

JButton btnRestart = new JButton("Restart");
btnRestart.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    {

    }
});

JButton btnNewWord = new JButton("Add New Word");
btnNewWord.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
{
try
{
    FileWriter fw = new FileWriter("Words.txt", true);
    PrintWriter pw = new PrintWriter(fw, true);

    String word = JOptionPane.showInputDialog("Please enter a word: ");

    pw.println(word);
    pw.close();
}
catch(IOException ie)
{
    System.out.println("Error Thrown" + ie.getMessage());
}
}
});

JButton btnHelp = new JButton("Help");
btnHelp.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e)
   {
       String message = "The word to guess is represented by a row of dashes, giving the number of letters and category of the word. \nIf the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions. \nIf the suggested letter does not occur in the word, the other player draws one element of the hangman diagram as a tally mark."
               + "\n"
               + "\nThe game is over when:"
               + "\nThe guessing player completes the word, or guesses the whole word correctly"
               + "\nThe other player completes the diagram";
       JOptionPane.showMessageDialog(null,message, "Help",JOptionPane.INFORMATION_MESSAGE);
   }
});

JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    {
        System.exit(0);
    }
});

ImageIcon icon = new ImageIcon("D:\\Varsity College\\Prog212Assign1_10-013803\\images\\Hangman1.jpg");
JLabel label = new JLabel();
label.setIcon(icon);
String  b[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(i = 0; i < buttons.length; i++)
{
    buttons[i] = new JButton(b[i]);

    panel.add(buttons[i]);
}

panel2.add(label);

panel3.add(btnRestart);
panel3.add(btnNewWord);
panel3.add(btnHelp);
panel3.add(btnExit);
}
public void readFromFile()
{
try
{
    BufferedReader reader = new BufferedReader(new FileReader("Words.txt"));
}
}

public static void main(String[] args) 
{
    Hangman frame = new Hangman();
    Box mainPanel = Box.createVerticalBox();
    frame.setContentPane(mainPanel);
    mainPanel.add(panel, BorderLayout.NORTH);
    mainPanel.add(panel2);
    mainPanel.add(panel3);
    frame.pack();
    frame.setVisible(true);
}

}

【问题讨论】:

  • 我建议将可能的单词加载到List 并使用Collections.shuffle 生成一个随机顺序,然后您可以从中采样。

标签: java


【解决方案1】:

创建一个方法将文件中的文字读入List。例如:

List<String> words = readFile();

要获取单词,请使用String#split(" ") 将行拆分为单词。将这些单词添加到列表中。然后只需使用:

Random yourRandom = new Random(words.size());
String word = words.get(yourRandom.nextInt());

你会从你的列表中得到随机词。

【讨论】:

    【解决方案2】:

    您可以使用ReadLine() 函数从文本文件中读取每一行。这将返回一个可以与fileLine.split(" ") 一起使用的字符串。这将为您提供一个数组,其中每个元素作为文件中的一个单词。

    如果您添加所有这些列表,您可以获得大小并选择一个介于 0 和 size() 之间的随机数,然后使用它来获取集合的字符串。

    您现在从刚刚读入的文件中获得了一个随机单词。

    示例代码:

    try{
        BufferedReader reader = new BufferedReader(new FileReader("Words.txt"));
        String line = reader.readLine();
        List<String> words = new ArrayList<String>();
        while(line != null) {
            String[] wordsLine = line.split(" ");
            for(String word : wordsLine) {
                words.add(word);
            }
            line = reader.readLine();
        }
    
        Random rand = new Random(System.currentTimeMillis());
        String randomWord = words.get(rand.nextInt(words.size()));
    } catch (Exception e) {
        // Handle this
    }
    

    【讨论】:

    • 每行一个单词,所以不需要line.split
    • @veer 谢谢,修复了代码 sn-p。如果可以保证一行不会有多个单词,则可以删除拆分。
    • 鉴于来自 OP 的以下声明 pw.println(word);,我将假设是的,可以删除拆分。 :-)
    • @JaunLloyd 它不工作怎么办,你看到错误还是没有得到正确的输出?如果您可以更具体一些,我们可以尝试为您提供一些帮助。
    • 不,我终于让它工作了,我使用了你给我的代码,但是我没有使用 void,而是使用了一个字符串,因此我使用了一个返回值......感谢您的帮助,我真的很感激它
    【解决方案3】:

    以下是有关如何解决此问题的简要指南:

    使用扫描仪读取数组:

    Scanner scanner = new Scanner(new File("words.txt"));
    while(scanner.hasNext()){
      // add scanner.nextLine() words to array 
    }
    

    数组填充完毕后,您可以在选择单词之前随机播放:

    Collections.shuffle(wordList);
    String pickWord = wordList.get(0);
    

    我在这里使用列表中的第一个条目,但您可以随机选择一个。

    【讨论】:

    • 你也可以为多个随机选择随机播放一次,因为每个元素都和第一个元素一样随机 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    相关资源
    最近更新 更多