简体   繁体   English

程序从数组中获取每第5个对象和第7个对象的唯一列表(List)

[英]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 % . 尝试使用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++;
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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