简体   繁体   中英

How to increment the variable names created jlabels using for loop?

java code:

for (int i = 0; i < 10;++i) {
   if (i == 9){
     lbl_ichar.setText(String.valueOf(word.charAt(i)));
   }
}

This code shows error message(compile time error:cannot find symbol symbol: variable class lbl_ichar) under word lbl_ichar .But I have already created jlabels of variable names lbl_0char , lbl_1char , lbl_2char ...... upto lbl_9char .

I want to call by the name lbl_ichar instead of using lbl_9char .Is that possible in java? If so how to code it?

It looks like you are trying to create a variable name dynamically at runtime:

JLabel lbl_1char = new JLabel();
JLabel lbl_2char = new JLabel();
// ...

for (int i = 0; i < 10; ++i) {
   lbl_ichar.setText(String.valueOf(word.charAt(i)));
   //  ^
}

This does not work. You can not create the variable name at runtime. Use an array instead:

JLabel[] lbl_char = new JLabel[10];
lbl_char[0] = new JLabel();
lbl_char[1] = new JLabel();
// ...

for (int i = 0; i < lbl_char.length; i++) {
   lbl_char[i].setText(String.valueOf(word.charAt(i)));
}

Or, even better, instead of using raw arrays, use an ArrayList :

List<JLabel> lbl_char = new ArrayList<>();
lbl_char.add(new JLabel());
lbl_char.add(new JLabel());
// ...

for (JLabel lbl : lbl_char) {
   lbl.setText("Whatever");
}

try to do something likewise,

JLabel lb_char[] = new JLable[10];

then after into Loop you can refer that labels like this way,

for (int i = 0; i < 10;++i) {

     lbl_char[i].setText(String.valueOf(word.charAt(i)));
} 

You cannot directly use loop variable i value like "lbl_ichar".

you want to change the value only if your i value is 9, or do you want to set new value for "lbl_9char" ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM