简体   繁体   中英

program to get a unique list (List) of every 5th and every 7th object from an array

this is my sample code

Object[] a=new Object[n];
for(int i=4;i<a.length;i+=5)
{
    System.out.println(a[i]);
}       
for(int i=6;i<a.length;i+=7)
{
    System.out.println(a[i]);
}

Try using Modulus operator % . No need to loop twice.

public static void main(String[] args) throws ParseException {
        //Object[] a = new Object[20];
        Object[] a = new Object[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
                16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
                32, 33, 34, 35 };

        for (int i = 0; i < a.length; i++) {
            if (i % 5 == 4 && i % 7 == 6) {
                System.out.println("Multiple of 5 and 7 both - " + a[i]);
            } else if (i % 5 == 4) {
                System.out.println("Multiple of 5 - " + a[i]);
            } else if (i % 7 == 6) {
                System.out.println("Multiple of 7 - " + a[i]);
            }
        }
    }

output

Multiple of 5 - 5
Multiple of 7 - 7
Multiple of 5 - 10
Multiple of 7 - 14
Multiple of 5 - 15
Multiple of 5 - 20
Multiple of 7 - 21
Multiple of 5 - 25
Multiple of 7 - 28
Multiple of 5 - 30
Multiple of 5 and 7 both - 35

you can use the counters instead.

Object[] a = new Object[n];

        int counter = 2;
        int elementsCounter = 5;

        for (int i = 0; i < a.Length; i++)
        {
            if (i == elementsCounter )
            {
                System.out.println(a[i]);
                elementsCounter += counter;
                counter++;
            }
        }

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