Java:如何从第二种方法获取变量以在第三种方法中工作?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java:如何从第二种方法获取变量以在第三种方法中工作?相关的知识,希望对你有一定的参考价值。
家庭背景
我正在为我的课程编写一个Java程序,其中:
生成一个介于1到100之间的10个随机数的数组
应用程序会将数组传递给计算的平均值方法,然后将计算的平均值方法返回给主方法
数组和数组中的平均值将传递到下面的方法中,在该方法中,将计算所有小于平均值的数字,并返回小于平均值的整数数并在main方法中显示。
这是我的初学者Java类,所以我对Java并不是最好的。我已经编程了大约一个半月。
TL; DR:我的问题是,我无法让第二种方法中的平均变量在第三种方法中工作以进行计算。
[在第三个方法中,我尝试调用另一个方法,例如:calcAverage(int [] array))
和public static double countBelow (int[] array, calcAverage(array))
// main method
public static void main (String[] args)
final int ARRAY_LENGTH = 10;
//array object is created
int array[] = new int [ARRAY_LENGTH];
//for loop that loops through the array
for (int rand = 0; rand < array.length; rand++)
// random number generator from 1-100
array[rand] = (int)(Math.random()*100);
//end of loop
//for loop that loops through the array
for (int rand = 0; rand < array.length; rand++)
// prints random numbers to the screen
System.out.printf("Numbers: %d \n", array[rand]);
//end of for loop
//passing the array to the second method
calcAverage(array);
//prints out average
System.out.print("Average is:");
System.out.println (calcAverage(array));
//passing array to the third method
countBelow(calcAverage(array));
// end of main method
//declaring second method for calculating average
public static double calcAverage(int[] array)
//declaring variables for the sum and average
double sum = 0;
double average = 0;
//for loop that loops through the array
for (int rand = 0; rand < array.length; rand++)
//computes the sum of the random numbers from first method
sum += array[rand];
//computes average
average = (sum / array.length);
//returns average to main method
return average;
//end of second method
//start of third method
public static int countBelow (int[] array, double average)
int scoresBelow = 0;
//for loop that loops through the array
for (int rand = 0; rand < array.length; rand++)
if (array[rand] < average)
scoresBelow ++;
else
return scoresBelow;
//end of class ArrayTest
我收到错误消息:
错误:ArrayTest类中的方法countBelow无法应用于给定类型;countBelow(calcAverage(array));^必需:int [],double找到:双原因:实际和正式论点清单的长度不同1个错误
[您要么需要在main方法中计算平均值,然后将其传递给countBelow
,要么在countBelow
中进行计算:
第一版-之前计算并传递给countBelow
// You pass the average already computed as a double argument:
public static double countBelow (int[] array, double average)
// Do what you must do...
// In the main method:
final int[] array = ...;
final double average = calcAverage(array);
countBelow(array, average);
第二版本 —直接在countBelow
]中计算平均值
// You only pass the array:
public static double countBelow(int[] array)
// You compute the average here:
final double average = calcAverage(array);
// Do what you must do...
// In the main method:
final int[] array = ...;
countBelow(array);
您需要在单独的步骤中执行此操作
您的countBelow
方法似乎有两个参数:int[] array
和calcAverage(array)
的结果,因此签名应为:
以上是关于Java:如何从第二种方法获取变量以在第三种方法中工作?的主要内容,如果未能解决你的问题,请参考以下文章