简体   繁体   English

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

[英]Randomly choose a word from a text file

I'm trying to do my assignment for college, and no where can i find a way to read from a text file and choose a random word from the list!我正在尝试完成我的大学作业,但我找不到从文本文件中读取并从列表中随机选择一个单词的方法! The assignment is about hangman, and the program is suppose to choose a random word from the list作业是关于刽子手,程序假设从列表中随机选择一个单词

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

}

Create a method to read the file's words into the List .创建一个方法将文件的单词读入List For eg:例如:

List<String> words = readFile();

To get the words use String#split(" ") to split the line into the words.要获取单词,请使用String#split(" ")将行拆分为单词。 Add those words into the list.将这些词添加到列表中。 Then just use:然后只需使用:

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

And you'll get the random word from your list.你会从你的列表中得到随机单词。

You can use the ReadLine() function to read each line from the text file.您可以使用ReadLine()函数从文本文件中读取每一行。 This will return a string that you can use with fileLine.split(" ") .这将返回一个可以与fileLine.split(" ")一起使用的字符串。 This will give you an array with each element as a word in the file.这将为您提供一个数组,其中每个元素都作为文件中的一个单词。

If you add all of these of a List you can then get the size and select a random number between 0 and size() , then use this to get the String for the collection.如果添加 List 的所有这些,则可以获取大小并选择 0 和size()之间的随机数,然后使用它来获取集合的字符串。

You now have a random word from the file that you just read in.您现在从刚刚读入的文件中获得了一个随机单词。

Sample Code:示例代码:

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
}

Here is a brief guide on how this could be approached:以下是有关如何解决此问题的简要指南:

Read to array, using, say a Scanner:读取数组,使用,说一个扫描仪:

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

After the array has been populated, you can shuffle prior to picking a word:填充数组后,您可以在选择单词之前进行随机播放:

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

I'm using the first entry in the list here, but you could pick a random one.我在这里使用列表中的第一个条目,但您可以随机选择一个。

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

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