[英]How do I find the average of the price?
我必须将数据存储在二维数组中,然后打印具有可用选项“否”的价格的平均值,任何人都可以帮助找到平均值。
public class Test {
public static void main(String[] args) {
double total = 0;
Products[][] names = new Products[][]{
{new Products("k7580", 6500, "yes")},
{new Products("k8570", 7333, "no")},
{new Products("k8580", 766, "no")},
{new Products("k6580", 288, "yes")}
};
for (int i = 0; i < names.length; i++) {
for (int j = 0; j < names[i].length; j++) {
String available = names[i][j].getAvailable();
if (available.equals("no")) {
total = total + names[i][j].getPrice();
}
}
System.out.println("");
}
// from here I am not able to find average
double average = total / names.length;
System.out.println("average of price :" + average);
}
}
您需要定义一个count
变量,根据您的 if 条件( available.equals("no")
)每次递增它以仅计算满足条件的元素:
double total = 0;
Products[][] names = new Products[][] { { new Products("k7580", 6500, "yes") },
{ new Products("k8570", 7333, "no") }, { new Products("k8580", 766, "no") },
{ new Products("k6580", 288, "yes") } };
int count = 0;
for (int i = 0; i < names.length; i++) {
for (int j = 0; j < names[i].length; j++) {
String available = names[i][j].getAvailable();
if (available.equals("no")) {
count++;
total +=names[i][j].getPrice();
}
}
System.out.println("");
}
// from here I am not able to find average
double average = total / count;
System.out.println("average of price :" + average);
如果您使用Java 8或更高版本,则可以使用它:
public static void main(String[] args) {
Products[][] names = new Products[][]{
{new Products("k7580", 6500, "yes")},
{new Products("k8570", 7333, "no")},
{new Products("k8580", 766, "no")},
{new Products("k6580", 288, "yes")}
};
Arrays.stream(names)
.flatMap(array -> Arrays.stream(array))
.filter(products -> products.getAvailable().equals("no"))
.mapToDouble(Products::getPrice)
.average()
.ifPresent(average -> System.out.println(
"average of price: " + average));
}
输出是:
average of price: 4049.5
如您所见,它很简洁。 我在这里使用了流。 Stream 有助于减少代码的冗长。
您不需要定义二维数组,只需维护一维产品数组并维护需要考虑平均的合格商品的数量(在您的情况下不可用的商品)
此代码将在单个循环中运行,无需嵌套循环。
public class Test {
public static void main(String[] args) {
double total = 0;
int notAvailableItems = 0;
Products[] names = new Products[]{
new Products("k7580", 6500, "yes"),
new Products("k8570", 7333, "no"),
new Products("k8580", 766, "no"),
new Products("k6580", 288, "yes")};
for (int i = 0; i < names.length; i++) {
Products product = names[i];
if (product.getAvailable().equals("no")) {
total = total + product.getPrice();
notAvailableItems++;
}
}
double average = total / (double) notAvailableItems;
System.out.println("average of price: " + average);
}
}
输出:
average of price: 4049.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.