我在stackoverflow上的第一篇文章!我也开始学习Java。 我正在尝试构建一个打印随机字母的程序,然后它应该写出以该字母开头的单词,并且它有一个要验证的类。
问题是当我生成randomNum以便从数组中获取randomLetter时,我无法与需要验证的类共享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"};
答案 0 :(得分:0)
问题是您使用randomNum
作为本地变量而不是数据成员。看起来你正在将方法的概念与类的概念混合在一起,阅读方法和类将非常有用。至于解决方案:
从jButtonPlayActionPerformed
方法中删除此行:
int randomNum;
而不是它,将randomNum
定义为类中的成员,但在方法之外,如下所示:
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"};