簡體   English   中英

嘗試編譯“while”語句時出現“無法訪問的語句”

[英]“unreachable statement” when trying to compile a “while” statement

我是Java的新手並且正在完成一些課程。 但是,在下面的代碼中,我在嘗試編譯時遇到錯誤“無法訪問的語句”。 關於我做錯了什么的指示?

public String getDeliveredList() {
   int count = 0;
   while (count < deliveredList.size()){
       return ("Order # " + count + deliveredList.get(count).getAsString());
       count++;
   }
}

從函數返回后,邏輯上它在該點之后就不再執行任何操作 - 永遠不會達到count++語句。

while (count < deliveredList.size()){

   // function always ends and returns value here
   return ("Order # " + count + deliveredList.get(count).getAsString());

   // this will never get run
   count++;
}

如果從函數返回,那么函數返回后的任何語句基本上都是無法訪問的語句,編譯器將對這些語句發出錯誤。

但是,以下代碼不會在返回后寫入語句時發出錯誤

void max(int a,int b)
{
    if(a>b) 
    {
        System.out.println(a+" is greater");
        return;
    }

    System.out.println(b+" is greater");
    return;
}

這是因為第一個return語句是在嵌套范圍內編寫的,而不是在函數范圍內立即可見。 當a> b時,程序執行只會通過第一個return語句。 如果不是這樣,則永遠不會執行該代碼塊。 因此,盡管返回后有語句,但代碼是可編譯的;

暫無
暫無

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

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