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

时间:2016-07-31 08:29:36

标签: 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++;
    }

你能解释第二个代码实际发生了什么,使它成为没有错误的东西。

2 个答案:

答案 0 :(得分:1)

带有while循环的代码在不同的范围内声明了两个Array.Sort(Index, Value.CreateIndexComparer()); 变量,因此与第一个代码段不同,您不会收到wordList错误。

您可以将while循环视为等效于:

Duplicate local variable

答案 1 :(得分:0)

首先将代码声明变量wordList两次而你只是不能这样做,你将得到错误int index = 0; LinearLayout rootview = (LinearLayout) findViewById(R.id.numbers); TextView wordList ; while(index<name.size()) { wordList = new TextView(this); wordList.setText(names.get(index)); rootview.addView(wordList); index++; } 变量已在范围中定义

为什么你重复自己,for循环为你做这个

我给你的建议不要在for循环中使用修订号更好地使用名称数组的长度

希望这个帮助

char poem[80]="Amar sonar bangla";
char rpoem[80];
int main()
   {
      char *pA, *pB;
      pA=poem;
      puts(pA);  /*line 1*/
      puts(poem);/*line 2*/
      pB=rpoem;
      while(*pA!='\0')
        {
          *pB++=*pA++ ;   
        }
     *pB='\0';
     puts(rpoem);/*line 3*/
     puts(pB);   /*line 4*/

    return 0;
  }
相关问题