java - 我们可以在Java中的while循环中定义一个变量吗?

标签 java android

这很奇怪,因为我写了这两个代码,如下所示,它们实际上具有相同的功能,但您可以看到第一个有错误,因为您声明了 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/

相关文章:

java - SignalR java 无法连接到服务器

java - 通过 HFile 将数据加载到 HBase 不工作

java - 如何将基类中的字段很好地复制到派生类中?

android - 更改偏好主题颜色

android - android中的新菜单?

android eclipse 创建谷歌地图时出错

java - 通用 BST 的实现

java - Java 中具有并行化的链式过滤器

java - IntelliJ IDEA - 无法解析方法

Android 持久的 MQTT 连接