java - Share variables from different function -
my first post here on stackoverflow! started learning java. i'm trying build program prints random letter, should write words begin letter, , has class verify.
the problem when generate randomnum in order randomletter array, can't share randomnum variable class needs verified.
private void jbuttonplayactionperformed(java.awt.event.actionevent evt) { int randomnum; randomnum = (int)(math.random()*palavras.length); system.out.println(""+randomnum); jlabelrandom.settext(introduce words begins : " + 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()}; (string w : words){ if(w.startswith(integer.tostring(palavras[randomnum]))){ // variable can't shared here, need here :) certas++; } } jlabelcertas.settext(integer.tostring(certas)); words = null; } public string[] palavras = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
the problem use randomnum
local variable instead of data member. seems mixing concept of method concept of class well, useful read methods , classes. solution:
remove row jbuttonplayactionperformed
method:
int randomnum;
instead of it, define randomnum
member inside class, outside methods, this:
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 begins : " + 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()}; (string w : words){ if(w.startswith(integer.tostring(palavras[randomnum]))){ // variable can't shared here, need here :) certas++; } } jlabelcertas.settext(integer.tostring(certas)); words = null; } public string[] palavras = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
Comments
Post a Comment