简体   繁体   中英

java appending strings doesn't work

I have a java program that has so many buttons with a text on it , whenever a user press the button the text inside a button should be added in an empty string ,

example,

String store = "";

if a user press 'A' then then the letter 'A' stored in the String variable 'store' if then a user press 'B'

then store must be equals to 'AB' , but this is not happening in my case , what happening is the previous String is simply replaced by the new one :S,

Here is the code,

String Text = "";

   for ( int count = 0; count < names.length; count++ ){

       if (event.getSource()==buttons[count]){
           Text += buttons[count].getText();
           JOptionPane.showMessageDialog(null, Text);
       }

   }

What am i doing wrong ? why the string is not adding new values ? why it replacing the previous ones ? :S

Is Text a local variable inside your action listener? In that case it will always be re-initialized. Make it a member of your class.

相当确定在按下第二个按钮之前,您不小心清除了Text变量。

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