gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:38:02 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com