[英]How to find the average of an array
下面是我的代碼。 我想出了如何通過復制我之前自己編寫的某人的代碼來找到平均值。 我的代碼不起作用的原因是:
private int[ ] array;
public Arraylab(int[] Val)
{
array = Val;
}
誰能向我解釋我的名為 numArray 的數組甚至需要上面的代碼。 數組名稱不在上述代碼中的任何位置,但它是必需的,因此代碼可以正常運行。 “數組”一詞在我之前編寫的“numArray”代碼中的位置,即使它看起來是正確的並且應該是正確的,它也不起作用。
class Arraylab {
private int[ ] array;
public Arraylab(int[] Val)
{
array = Val;
}
public double Average()
{
double total = 0;
for (int val : array)
{
total = total + val;
}
return total / array.length;
}
public static void main(String[] args)
{
int[] numArray = {10,6,3,2,6};
Arraylab obj = new Arraylab(numArray);
System.out.println(obj.Average());
}
}
}
您正在混淆 object 方向和 static 方法調用,這就是您遇到問題的原因。
此行正在創建您的 class Arraylab obj = new Arraylab(numArray);
的新實例這與您的主要方法所在的實例不同,這就是您需要使用public Arraylab(int[] Val)
方法初始化array
的原因。
簡單的解決方案是制作Average
方法static
並將您的數組直接傳遞給它:
class Arraylab {
//We can return the average value from this method if we pass an int[] array into the method
//This method also needs the static keyword so that we can call it directly
public static double Average(int[] array)
{
double total = 0;
for (int val : array)
{
total = total + val;
}
return total / array.length;
}
public static void main(String[] args)
{
//Create the array
int[] numArray = {10,6,3,2,6};
//Pass the numArray into the Average method and store the returned result
double result = Average(numArray);
//Print the result
System.out.println(result);
}
}
如果您使用 java 8 或更高版本,則可以使用 Streams。
First of all, create a Stream from the array with Arrays.stream that'll return an IntStream which has the function IntStream.average .
最后一個方法將返回一個OptionalDouble ,正如文檔所說。 OptionalDouble.orElse如果存在則返回值,否則返回自定義值(例如 NaN)。
代碼很簡單
import java.util.Arrays;
public class StackOverflow {
public static void main(String[] args) {
int[] numbers = {1, 56, 84, -2, 2};
double average;
average = Arrays.stream(numbers).average().orElse(Double.NaN);
System.out.println(average);
}
}
Stream 解決方案。 如果計算了平均值,則打印它,否則如果未計算,則顯示您選擇的信息性消息。
int[] numArray = {10,6,3,2,6};
OptionalDouble opd = Arrays.stream(numArray).average();
opd.ifPresentOrElse(System.out::println,
()->System.out.println("Empty Array"));
印刷
5.4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.