2015-07-10 290 views
0

爲什麼我無法將appleArray,blueberryArray和peanutArray發送到calcTotalPies方法?無法將數組傳遞給方法

final int MAX_PIES = 81; 
final int MAX_PER_TYPE = 27; 

String typeOfPie = getPieType(); 
while (!typeOfPie.equalsIgnoreCase("q")) { 
    if (typeOfPie.equalsIgnoreCase("apple")) { 
     String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE); 
    } 
    else if (typeOfPie.equalsIgnoreCase("blueberry")) { 
     String[] blueberryArray = fillBlueberry(typeOfPie, MAX_PER_TYPE); 
    } 
    else if (typeOfPie.equalsIgnoreCase("peanut")) { 
     String[] peanutArray = fillPeanut(typeOfPie, MAX_PER_TYPE); 
    } 
    typeOfPie = getPieType(); 
} 

if (typeOfPie.equalsIgnoreCase("q")) { 
     int totalPies = calcTotalPies(appleArray, blueberryArray, peanutArray); 
} 

回答

0

當你的代碼執行到達你的方法時,如果else塊聲明內部的while循環,你的數組聲明已經結束並且它們不可訪問。所以你需要在循環之外初始化它們。

試試這個

final int MAX_PIES = 81; 
final int MAX_PER_TYPE = 27; 

String[] peanutArray = null; 
String[] blueberryArray = null; 
String[] appleArray = null; 

String typeOfPie = getPieType(); 
while (!typeOfPie.equalsIgnoreCase("q")) { 
    if (typeOfPie.equalsIgnoreCase("apple")) { 
     appleArray = fillApple(typeOfPie, MAX_PER_TYPE); 
    } else if (typeOfPie.equalsIgnoreCase("blueberry")) { 
     blueberryArray = fillBlueberry(typeOfPie, MAX_PER_TYPE); 
    } else if (typeOfPie.equalsIgnoreCase("peanut")) { 
     peanutArray = fillPeanut(typeOfPie, MAX_PER_TYPE); 
    } 
    typeOfPie = getPieType(); 
} 

if (typeOfPie.equalsIgnoreCase("q")) { 
    int totalPies = calcTotalPies(appleArray, blueberryArray, peanutArray); 
} 
1

局部變量總是一個塊中聲明和僅在該塊(注意:方法體或if的主體或一個環也是一個塊)活着。

你宣佈appleArray,只在其周圍if -blocks blueberryArraypeanutArray,因此他們不是在最低if - 塊活着。編譯器應該告訴你一些這些數組沒有被定義。

+0

只是爲了添加評論@丹:像Java和C語言中有一個叫做概念*「塊範圍*」。代碼塊由大括號分隔。塊範圍確保塊內聲明的變量不會污染它們出現的其他代碼域的名稱空間。這使您的項目中的模塊保持彼此分離。 – scottb