使用for循环从BitSet打印值

时间:2017-10-05 17:54:06

标签: java bitset

我想用单个for循环(或其他形式的迭代)打印我目前所拥有的内容,并且只打印一个标志声明,但我无法使用'标记#'对于每个定义的值。应该有5位 - 我有 - 但只有一个标记要迭代。我使用带有模数(%)的可分性来对每个标志进行排序。代码如下。

import java.util.*;

public class BitSet {

    public static void main(String args[]) {
        BitSet flags1 = new BitSet(5);
        BitSet flags2 = new BitSet(5);
        BitSet flags3 = new BitSet(5);
        BitSet flags4 = new BitSet(5);
        BitSet flags5 = new BitSet(5);

        for (int i = 0; i < 6; i++) {
            if((i % 1) == 0) flags1.set(i);
            if((i % 2) == 0) flags2.set(i);
            if((i % 3) == 0) flags3.set(i);
            if((i % 4) == 0) flags4.set(i);
            if((i % 5) == 0) flags5.set(i);
        }

        System.out.println("Numbers divisible by 1: " + flags1);
        System.out.println("Numbers divisible by 2: " + flags2);
        System.out.println("Numbers divisible by 3: " + flags3);
        System.out.println("Numbers divisible by 4: " + flags4);
        System.out.println("Numbers divisible by 5: " + flags5);
    }
}

1 个答案:

答案 0 :(得分:0)

使用数组(或ArrayList<BitSet>)存储位集,然后迭代数组。

import java.util.*;



  public class BitSet {
        public static void main(String args[]) {
           BitSet[] flags = new BitSet[5];
        for (int i = 0; i < flags.length; i++) {
           flags[i] = new BitSet(5);
        }

        for (int i = 1; i < 6; i++) {
            for (int j = 1; j <= 5; j++) {
                if (i % j == 0) {
                  flags[j - 1].set(i);
                }
            }
        }

        for (int i = 0; i < flags.length; i++) {
            System.out.printf("Numbers divisible by %d: %s%n", i + 1, flags[i]);
        }
    }