如何增加最终的整数变量?
Eclipse 提供了 final
但我无法增加 i
变量。
@Override
public void onClick(View v) {
final TextView tv = (TextView) findViewById(R.id.tvSayac);
int i = 1;
do {
try {
new Thread(new Runnable() {
public void run() {
tv.post(new Runnable() {
public void run() {
tv.setText(Integer.toString(i));
}
});
}
});
i++;
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (i < 16);
}
Eclipse is offering final
but I can't increase the i
variable.
@Override
public void onClick(View v) {
final TextView tv = (TextView) findViewById(R.id.tvSayac);
int i = 1;
do {
try {
new Thread(new Runnable() {
public void run() {
tv.post(new Runnable() {
public void run() {
tv.setText(Integer.toString(i));
}
});
}
});
i++;
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (i < 16);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Final 是初始化后不能更改的实体。
Final (Java)
你可以做的是在范围内创建一个变量do/while 循环最终具有 i 的值并将其发送到函数中。
A final is an entity that can not be changed after it is initialized.
Final (Java)
What you could do is create a variable within the scope of the do/while loop that is final with the value of
i
and send that into the function.这里最简单的解决方案是创建一个类:
The easiest solution here is to create a class:
我认为可以创建变量
i
的本地副本。试试这个:通过创建最终的本地副本:
i
而不是localCopy
。我想你也想启动线程...
编辑:确实,你是对的。您必须在循环内创建本地最终副本。检查新代码。
I think it is possible to create a local copy of the variable
i
. Try this:By creating a final local copy:
i
and notlocalCopy
.I suppose you want to start the Thread as well...
EDIT: Indeed, you were right. You have to create the local final copy inside the loop. Check the new code.
最终变量只能初始化一次,不一定是在定义它时初始化。它可以在构造函数中随时设置,但只能设置一次。在您使用 i++ 递增 i 的情况下,您试图再次将递增的值分配给 i ,这是不允许的。
A final variable can only be initialized once not necessarily when you are defining it. It can be set any time within the constructor , but only once. In your case when you are incrementing i using i++, you are trying to assign the incremented value to i again which is not allowed.
您可以创建一个计数器类像这样并递增它。这样,Counter 对象的引用可能是最终的,但您仍然可以设置它的值?
You could create a counter class like that and increment it. This way, the reference of the Counter object could be final but you could still set its value ?
我所做的是添加:
在此之前:
之后您将能够像往常一样使用您的变量,而不必将其标记为最终变量。
What I did was add a:
Before this:
And you'll be able to use your variable as usual after that, without having to mark it as final.