0

ラベル「JLabel lblWord = new JLabel(randomWord)」として実行すると、ラベルは表示されませんが、system.out.println(randomWord) として実行すると、null が返されます...単語の 1 つを返すと仮定しますテキストファイルにあるのですが、コード全体を一番下に移動しても機能しないようです

import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.List;

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

    public static String readWord()
    {
        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(" ");
                boolean addAll = words.addAll(Arrays.asList(wordsLine));
                line = reader.readLine();
            }
            Random rand = new Random(System.currentTimeMillis());
            String randomWord = words.get(rand.nextInt(words.size()));
        }catch (Exception e){

        }
        return randomWord;
    }

    public Hangman()
    {

        JButton[] buttons = new JButton[26];

        panel = new JPanel(new GridLayout(0,9));
        panel2 = new JPanel();
        panel3 = new JPanel();
        panel4 = 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 lblWord = new JLabel(randomWord);
        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);
        panel4.add(lblWord);
    }

    public static void main(String[] args) 
    {

        System.out.println();
        Hangman frame = new Hangman();
        Box mainPanel = Box.createVerticalBox();
        frame.setContentPane(mainPanel);
        mainPanel.add(panel, BorderLayout.NORTH);
        mainPanel.add(panel2);
        mainPanel.add(panel4);
        mainPanel.add(panel3);
        frame.pack();
        frame.setVisible(true);
    }
}
4

1 に答える 1

3

randomWord 変数は 2 回宣言されます。1 回目は Hangman クラスで宣言され、そこで null のままになり、2 回目は readWord メソッドでランダムな文字列で満たされ、返されます。これらは 2 つの異なる、完全に異なる変数であることを理解してください。また、内部で宣言されている変数にはreadWord()、このメソッドに限定されたスコープがあります。つまり、このメソッドの外には存在しません。

ソリューション:

  • Hangman クラスにある randomWord 変数を削除してください。誤解を招くため、役に立たないよりも悪いことです。
  • 必要なときに readWord() メソッドを呼び出して、ランダムな単語を取得します。それが、そもそもこの方法がある理由です。
  • 問題を抱えている2つの概念である変数のスコープと変数のシャドウイングについて調べてください。
  • 私は物事を少し改善し、すべての単語を に入れたらArrayList<String>単語ファイルを読みます。次に、ランダムな単語が必要なときに、ArrayList からランダムな単語を取得します。同じファイルを何度も読み直す必要はありません。
于 2012-08-20T23:46:06.350 に答える