简体   繁体   中英

Loop through ArrayList

I'm trying to loop through an ArrayList an get the current value of the loop instance.

public ArrayList<Double> getCurrent(double x) {

    ArrayList<Double> list = new ArrayList<>(); 

    list.add(x);

    ArrayList<Double> list1 = new ArrayList<>(); 

    double sum = 0;
    for (int i = 0; i < list.size(); i++) {
        sum += list.get(i);
        list1.add(sum);
    }

    return list1;

}

Here are my JSP file. Note the loop goes through my ArrayList history, and the values I want to parse into the new ArrayList from the method getCurrent(double x) takes ret .

<% for (history his : history) {


    double ret = his.getRet();
    double dep = his.getDeposit();
    String res = his.getRes();

    if (res.equals("Loss")) {
        ret = -dep;
         }

 %>

<h1><%=his.getCurrent(ret) %></h1>

<%} %>

This gives my an ArrayList which consist of the correct values, but NOT added with the previous values. The ArrayList now shows: [30.0, -5.0, 20.0] which is correct values. However, I want it to display: [30, 25, 45] so the values are added together with all previous values.

I believe what you want to do is to pass the double values to this function and then the function will return the list with the calculated values.

According to your code whenever the function is invoked a new Arraylist is declared every time . Thus there are no previous values , there. If you want the output to be like what you have mentioned then declare the list outside the function . Once it is outside there is no need to declared it again and again. It will retain all the previous values and when you will do your calculation it will give you your expected output.

I believe you want to get some but your declared variable is not final. Every function call will reset its value and you will not be able to get the required results. Furthermore, the statement:

 sum += list.get(i);

is not as much appropriate to all compilers and IDE's and this can cause runtime error and may contain garbage if not properly handled. I prefer using this modified code.

 Final double sum = 0; for (int i = 0; i < list.size(); i++) { sum = sum + list.get(i); list1.add(sum); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM