共享来自不同函数的变量

Share variables from different function

我在 Whosebug 上的第一个 post!我也开始学习Java。 我正在尝试构建一个打印随机字母的程序,然后它应该写出以该字母开头的单词,并且它有一个 class 来验证。

问题是当我生成 randomNum 以从数组中获取 randomLetter 时,我无法与需要验证的 class 共享 randomNum 变量。

private void jButtonPlayActionPerformed(java.awt.event.ActionEvent evt) {                                            

    int randomNum;

    randomNum = (int)(Math.random()*palavras.length);
    System.out.println(""+randomNum);


    jLabelRandom.setText(Introduce words that begins with : " + palavras[randomNum]);


}                                           

private void jButtonVerificarActionPerformed(java.awt.event.ActionEvent evt) {                                                 

    int certas = 0;

    String[] words = {jTextField1.getText(), jTextField2.getText(), jTextField3.getText(), jTextField4.getText(),
                      jTextField4.getText()};         

    for (String w : words){

        if(w.startsWith(Integer.ToString(palavras[randomNum]))){ // This variable can't be shared here, but I need it here :)
            certas++;
        }
}

     jLabelCertas.setText(Integer.toString(certas));
     words = null;

}                                                

public String[] palavras = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};

问题是您将 randomNum 用作局部变量而不是数据成员。看来您也将方法的概念与 class 的概念混合在一起,阅读方法和 classes 将非常有用。关于解决方案:

从您的 jButtonPlayActionPerformed 方法中删除此行:

int randomNum;

取而代之,将 randomNum 定义为 class 内部的成员,但在您的方法之外,如下所示:

private int randomNum;

private void jButtonPlayActionPerformed(java.awt.event.ActionEvent evt) {                                            

    randomNum = (int)(Math.random()*palavras.length);
    System.out.println(""+randomNum);


    jLabelRandom.setText(Introduce words that begins with : " + palavras[randomNum]);


}                                           

private void jButtonVerificarActionPerformed(java.awt.event.ActionEvent evt) {                                                 

    int certas = 0;

    String[] words = {jTextField1.getText(), jTextField2.getText(), jTextField3.getText(), jTextField4.getText(),
                      jTextField4.getText()};         

    for (String w : words){

        if(w.startsWith(Integer.ToString(palavras[randomNum]))){ // This variable can't be shared here, but I need it here :)
            certas++;
        }
}

     jLabelCertas.setText(Integer.toString(certas));
     words = null;

}                                                

public String[] palavras = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};