简体   繁体   中英

Int in string does not change when i change the int value

So I'm making a code that uses int value in a string(hardcoded btw), it works but when I incremented the value of the int by button click, the int in the string does not change as the increment.

int indexOfQuestion= 1; 
numberOfQuestion.setText("Question " + indexOfQuestion + " from " + lengthOfQuestion + " :" );
switch(v.getId()):
case R.id.next:
indexOfQuestion = indexOfQuestion+1;

so when I clicked the button, indexOfQuestion in numberOfQuestion stays 1. How do i change it automatically as I intended without long verbose codes? thanks

What actually you are doing is calling this statement each time whenever you click the button:

 int indexOfQuestion = 1; 

What you need to do is change the scope of int indexOfQuestion = 1; and take it to outside of the method body.

public class Test {
     private int indexOfQuestion = 1; 
}

Instead of putting it inside onClick function.

it won't change because you setText before you increment int value. if you want to apply changes, you should setText again after the incrementation.

int indexOfQuestion= 1;

numberOfQuestion.setText("Question " + indexOfQuestion + " from " + lengthOfQuestion + " :" );
switch(v.getId()):
case R.id.next: indexOfQuestion = indexOfQuestion+1;
numberOfQuestion.setText("Question " + indexOfQuestion + " from " + lengthOfQuestion + " :" );

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