java list 数值求和,如何对arrayList中的值求和

I am trying to create a console application where i take input from the user asking for total area then i ask the user the amount of structures that our in that area and then I store the values in the list what I am trying t do is substract the total area by structure are but i cant sum the values from the List

package lawn;

import java.util.Scanner;

import java.util.List;

import java.util.ArrayList;

/**

*

* @author norbe

*/

public class Lawn {

private double lenght, width;

private double totalArea;

private double structureArea;

private double tot;

List list = new ArrayList();

public Lawn (){

return;}

public Lawn(double Lenght, double Width) {

this.lenght = Lenght;

this.width = Width;

}

public double getWidth() {

return width;

}

public void setWidth(double Width) {

this.width = Width;

}

public double getLenght() {

return lenght;

}

public void setHeight(double Lenght) {

this.lenght = Lenght;

}

public void getTotalArea() {

Scanner sc = new Scanner(System.in);

double lenght;

double width;

System.out.println("please enter Total lenght :\t ");

lenght = sc.nextDouble();

if (lenght >= 0.0) {

System.out.println("Please enter width :\t ");

width = sc.nextDouble();

if (width > 0.0) {

totalArea = lenght * width;

System.out.println("Your total area is :\t " + totalArea);

} else {

System.out.println("Invalid entry");

}

} else {

System.out.println("Invalid entry");

}

}

public void getStructureArea() {

Scanner sc = new Scanner(System.in);

/*double lenght;

double width;*/

System.out.println("please enter Structure lenght :\t ");

lenght = sc.nextDouble();

if (lenght >= 0.0) {

System.out.println("Please enter Structure width :\t ");

width = sc.nextDouble();

if (width > 0.0) {

structureArea = lenght * width;

list.add(structureArea);

System.out.println("Your Structure area is :\t " + structureArea);

} else {

System.out.println("Invalid entry");

}

} else {

System.out.println("Invalid entry");

}

System.out.println(list);

}

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

double tot = 0;

Lawn lawn = new Lawn();

lawn.getTotalArea();

System.out.println("Please enter number of structures : ");

Scanner sc = new Scanner(System.in);

int structures = sc.nextInt();

for (int count = 1; count <= structures; count++) {

lawn.getStructureArea();

}

double sum = 0;

/* for (Double item : list) {

tot += item.structureArea;

}*/

}

}

解决方案

You can do it by using a java 8 lambda:

Double total = lawn.list.stream().mapToDouble(i -> i).sum();

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值