我试图将计数器变量读入另一个方法(printPartiallyFilledArray),以便计算和打印数组中正确数量的字符串元素。但是每当我尝试编译时,它都会说我无法找到计算变量。我怎样才能使第二种方法知道计数器变量的值?
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]); }
}
}
答案 0 :(得分:0)
有两种方法可以告知方法计数器的值:
例如:
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);
答案 1 :(得分:0)
您也可以使用
传递计数器变量public static void printPartiallyFilledArray(String[] array, int counter)
并使用它。