这很奇怪,因为我写了这两个代码,如下所示,它们实际上具有相同的功能,但您可以看到第一个有错误,因为您声明了 TextView(名称为:wordlist)两次,但正如您所看到的第二个代码没有错误,虽然它的作用与第一个代码相同,但采用 while 循环的形式。
第一个代码:
int index = 0;
LinearLayout rootview = (LinearLayout) findViewById(R.id.numbers);
TextView wordList = new TextView(this);
wordList.setText(names.get(index));
rootview.addView(wordList);
index++;
TextView wordList = new TextView(this);
wordList.setText(names.get(index));
rootview.addView(wordList);
第二个代码:
int index = 0;
LinearLayout rootview = (LinearLayout) findViewById(R.id.numbers);
while(index<2) {
TextView wordList = new TextView(this);
wordList.setText(names.get(index));
rootview.addView(wordList);
index++;
}
您能否解释一下第二个代码实际发生了什么,使其没有错误。
最佳答案
带有 while 循环的代码在不同的作用域中声明了两个 wordList
变量,因此与第一个代码段不同,您不会收到 Duplicate local variable
错误。
您可以将 while 循环视为等效于:
{
TextView wordList = new TextView(this);
wordList.setText(names.get(index));
rootview.addView(wordList);
index++;
}
{
TextView wordList = new TextView(this);
wordList.setText(names.get(index));
rootview.addView(wordList);
index++;
}
关于java - 我们可以在Java中的while循环中定义一个变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38682162/