gpt4 book ai didi

java - 使用数组作为方法 (Java)

转载 作者:行者123 更新时间:2023-12-01 22:01:19 24 4
gpt4 key购买 nike

我在编译我的类时遇到问题。它给我错误,例如“无法取消引用 double ”和“找不到符号”。

潜水员是:

 public class MinilabArraysDriver{
public static void main(String[ ] args){
//create a 1d array of ints
int[ ] array1d = { 8, 8, 7, 5, 3 };

//call mean1d Method to find the mean (note the static call...)
double theMean = MinilabArrays.mean1d(array1d);

//print the original array and the mean
System.out.print("The mean of: { ");
for (int i=0; i<array1d.length; i++){
if (i != 0)
System.out.print(" ");
//print first for separation (except before first element)
System.out.print(array1d[i]);
}
System.out.print(" } is: " + theMean);
//------------------------------------------------------------
System.out.println("\n\n");
//create a 2d array of doubles
double[ ][ ] array2d = {{ 3.4, 5.1, 8.0},
{ 5.23, 8.2 },
{ 10.7 },
{ 2.9 }
};
//call sum2d to get the sum
double total = MinilabArrays.sum2d(array2d);

//print the 2D array
for (int row=0; row<array2d.length; row++){
System.out.println();
for (int col=0; col<array2d[row].length; col++)
System.out.print(array2d[row][col] + "\t");
}
//print the result
System.out.println("\n\nTotal of 2d array is: " + total);
System.out.println("\n\n");
}
}

这是我正在尝试编写的类:

public class MinilabArrays{
public static double mean1d(int[ ] theMean){
double total = 0;
for (int i = 0 ;i < theMean.length ; i++){
total = total + theMean [ i ];
total = total / theMean.length;
return total;
}
}

public static double sum2d(double [ ] theSum){
double total2, total3, total4 = 0;
for(int row=0 ; row < theSum.length ; row++){
for (int col=0 ; col<theSum[row].length ; col++)
total2 = total2 + theSum[col];
}
total3 = total3 + theSum[row];
total4 = total3 + total2;
return total4;
}
}

对于“mean1d”,我试图找到给定数字的平均值,而对于“sum2d”,我试图找到给定数字的总和。

抱歉,如果我的代码很愚蠢或愚蠢。如果它不允许我编译,我就无法检查它。

谢谢你帮助我!

最佳答案

您通过在参数中传递 2D 数组来调用 sum2d 方法,并将该方法声明为 1D 数组作为参数。

MinilabArrays.java

public static double sum2d(double[][] theSum) {
double total2 = 0;
for (int row = 0; row < theSum.length; row++) {
for (int col = 0; col < theSum[row].length; col++){
total2 = total2 + theSum[row][col];
}
}
return total2;
}

关于java - 使用数组作为方法 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33491475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com