2015-09-16 32 views
1

我想讀取一個計數器變量到另一個方法(printPartiallyFilledArray)爲了計算和打印數組中的正確數量的字符串元素。然而,無論何時我嘗試編譯,它都說我無法找到計算變量。我怎樣才能讓第二個方法知道計數器變量的值?試圖讀取int計數器到字符串方法[java]

public static void main(String [] args) 
{ 
    // Instantiate a String array that can contain 10 items. 
    Scanner keyboard = new Scanner(System.in); 
    int ARRAY_SIZE = 10; 
    String[] array = new String[ARRAY_SIZE]; 
    int counter = 0; 


    // Read names of subjects into this array 
    // and count how many have been read in. 
    // There may be fewer than 10. 
    System.out.println("Please enter a subject name or enter q to quit: "); 
    String subject = keyboard.nextLine(); 

    while(subject.equals("q")!=true && counter<ARRAY_SIZE) 
    { 
     array[counter] = subject; 
     counter++; 
     System.out.println("Please enter a subject name or enter q to quit: "); 
     subject = keyboard.nextLine(); 

    } 

    // Call printPartiallyFilledArray to print the names in the array. 
    printPartiallyFilledArray(array); 

} 


/** 
* Method printPartiallyFilledArray prints the String values 
* in a partially-filled array, one per line. Only the 
* significant items in the array should be printed. 
* 
* @param array the array of Strings to be printed on the screen 
* @param count the number of items in the partially-filled array 
*/ 
    public static void printPartiallyFilledArray(String[] array) 
    { 

    System.out.println("The array elements: "); 
     for (int i = 0; i < counter; i++){ 
     System.out.println(array[i]); } 

    } 

}

+1

聲明它在你的主要方法之外 –

+0

好的,謝謝你,我會試試這個。 – VNrutgib

+0

您的代碼在我的本地IntelliJ安裝程序中生成並運行良好。你準確得到什麼錯誤? –

回答

0

有兩種方法來通知方法對計數器的值:

  1. 定義變量計數器全球範圍內,主要的功能之外。這將允許它始終知道全局更新的計數器變量的值。

例如:

public class Solution{ 
public static int counter =0; 

    public static void main(String[] args){ 
    ---do things as before---- 
    } 

    public static void printPartiallyFilledArray(String[] array){ 
    ---do things as before---- 
    } 
} 
  • 通過重新定義函數參數傳遞計數器功能printPartiallyFilledArray的值:

    printPartiallyFilledArray(String[] array, int counter) 
    
  • 並在代碼中調用

    printPartiallyFilledArray(array, counter); 
    
    0

    您也可以通過計數器變量與

    public static void printPartiallyFilledArray(String[] array, int counter) 
    

    ,並使用它。