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]); }
}
}
聲明它在你的主要方法之外 –
好的,謝謝你,我會試試這個。 – VNrutgib
您的代碼在我的本地IntelliJ安裝程序中生成並運行良好。你準確得到什麼錯誤? –