簡體   English   中英

從文本文件中隨機選擇一個單詞

[英]Randomly choose a word from a text file

我正在嘗試完成我的大學作業,但我找不到從文本文件中讀取並從列表中隨機選擇一個單詞的方法! 作業是關於劊子手,程序假設從列表中隨機選擇一個單詞

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 例如:

List<String> words = readFile();

要獲取單詞,請使用String#split(" ")將行拆分為單詞。 將這些詞添加到列表中。 然后只需使用:

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

你會從你的列表中得到隨機單詞。

您可以使用ReadLine()函數從文本文件中讀取每一行。 這將返回一個可以與fileLine.split(" ")一起使用的字符串。 這將為您提供一個數組,其中每個元素都作為文件中的一個單詞。

如果添加 List 的所有這些,則可以獲取大小並選擇 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
}

以下是有關如何解決此問題的簡要指南:

讀取數組,使用,說一個掃描儀:

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

我在這里使用列表中的第一個條目,但您可以隨機選擇一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM