Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,697 questions

57,005 answers

573 users

How to sum numbers in ArrayList only those between x and y with Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.Arrays;
 
public class SumNumbersInArrayListOnlyThoseBetweenXandY_Java {
    public static void main(String[] args) {
        ArrayList<Integer> alist = new ArrayList<Integer>(Arrays.asList(1, 4, 9, 3, 6, 2, 3, 2));
 
        int x = 2;
        int y = 4;
         
        int i = 0, total = 0;
        while (i < alist.size()) {
            if (alist.get(i) >= x && alist.get(i) <= y) { // 4 3 2 3 2
                total += alist.get(i);
            }
            i++;
        }
         
        System.out.println(total);
    }
}
 
    
    
/*
run:
     
14
     
*/

 



answered Aug 18, 2024 by avibootz
edited Aug 18, 2024 by avibootz
...