簡體   English   中英

我們可以在Java的while循環中定義變量嗎?

[英]Can we define a variable in a while loop in Java?

這很奇怪,因為我寫了這兩個代碼,實際上,它們具有相同的功能,但是您可以看到第一個代碼有錯誤,因為您兩次聲明了一個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++;
}

第一個代碼,您兩次聲明了變量wordList ,而您根本做不到,您將得到錯誤的wordList變量已在作用域中定義

第二個為什么要重復自己,for循環為您做到這一點

我對您的建議不要在循環中使用修訂號更好地使用名稱數組的長度

希望這個幫助

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++;
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM