如何在类之间调用数组



你好,我是java新手,所以请温柔一点,

class Result{
public float Mean(){
//find the mean of the array
}
public float lowest(){
// find the lowest
}
}

public class Main{
public static void main(String[] args) {
float arr[] = {1.1,2.2,3.3};
}  
}

我想做的是从Main获取数组arr,并将其带到类Result中,以便使用它在CCD_ 4和CCD_。

谢谢。

尝试将数组添加为Result/Solve的构造函数的一部分,然后可以在创建的实例中使用数字。

class Solve {
final float[] numbers;
public Result(final float[] numbers){
this.numbers = numbers;
}
public float mean(){
//find the mean using the this.numbers
}
public float lowest(){
// find the lowest using this.numbers
}
}
public class Main{
public static void main(String[] args) {
float numbers[] = new float[]{1.1,2.2,3.3};
Solve solve = new Solve(numbers);
float mean = solve.mean();
float lowest = solve.lowest();

System.out.println("Mean: " + mean);
System.out.println("Lowest: " + lowest);
}
}

另一种选择是使方法成为静态的,并将数字作为方法的一部分进行传递,类似于Math类。

class Solve {

public static float mean(float[] numbers){

}

public static float lowest(float[] numbers) {

} 
} 
public class Main{
public static void main(String[] args) {
float numbers[] = new float[]{1.1,2.2,3.3};
float mean = Solve.mean(numbers);
float lowest = Solve.lowest(numbers);
System.out.println("Mean: " + mean);
System.out.println("Lowest: " + lowest);
}
}

以下是我处理此问题的方法:

结果类别:

class Result {
public static float mean(float... arr) { //make the method static, and have it take the array as a parameter
float sum = 0f;
for (float f : arr) { //add each number in the array to the sum variable
sum += f;
}
return sum / arr.length; //return sum / length, which is average
}
public static float lowest(float... arr) { //same as the above method
float lowest = arr[0];
for (float f : arr) { //loop through the array
if (f < lowest) { //if this number is lower than the current "lowest" number, set lowest to be this number
lowest = f;
}
}
return lowest; //return the lowest number
}
}

主要类别:

public class Main {
public static void main(String[] args) {
float[] arr = new float[] { 1.1f, 2.2f, 3.3f }; //here's the array
System.out.println(Result.mean(arr)); //I pass it to the method as a parameter
System.out.println(Result.lowest(arr)); //same here
}
}

另一种解决方案是使用Java流而不是for循环。Java流可能比循环更复杂,但它们可能更干净、更容易阅读。以下是我如何使用流重写Result类:

class Result {
public static float mean(float... arr) {
return (float) IntStream.range(0, arr.length)
.mapToDouble((i) -> arr[i])
.average()
.getAsDouble(); //returns the average of the array
}
public static float lowest(float... arr) {
return (float) IntStream.range(0, arr.length)
.mapToDouble((i) -> arr[i])
.min()
.getAsDouble(); //returns the minimum value in the array
}
}

将数组作为参数传递给其他对象的方法。

float[] arr = { 1.1F, 2.2F, 3.3F } ;
Result r = new Result() ;
float output = r.lowest( arr ) ;

在方法上定义该参数。

class Result{
public float mean( float[] input ){
// … find the mean of the array
}
public float lowest( float[] input ){
// … find the lowest
}
}

请在IdeOne.com上实时查看此代码。

在Java中,将参数传递给方法是一项最基本的技能。您应该学习Oracle的Java教程,并查阅教科书以了解基础知识。

最新更新