2

So I am trying to create an AList of AClass(es) with a 7-switch String parameter where each character is either on [1] or off [0], E.g: 0011010.

ArrayList<AClass> AList = new ArrayList<AClass>();    

public BClass() {
    // I believe there is 128 unique ways to arrange between 0000000 and 1111111
    for (int i = 0; i < ?; i++) {
        // I assume I would need to create the String some how here and use that.
        String str;
        AList.add(new AClass("0000000"));

        / * Each loop would create a new one, you get the idea.
        AList.add(new AClass("1000000"));
        AList.add(new AClass("1100000"));
        AList.add(new AClass("1110000"));
        ...
        ...
        AList.add(new AClass("1001010"));
        ...
        ...
        AList.add(new AClass("1111111"));
        */
    }
}

What is the most efficient way to create all 128 unique parameter AClass(es)?

Edited: Mistakenly started at 0000001 instead of 1000000

YCF_L
  • 49,027
  • 13
  • 75
  • 115
Daedric
  • 512
  • 3
  • 22

2 Answers2

3

You can use Integer.toBinaryString(int i) and String.format to complete your String with 0 in left:

for (int i = 0; i < 128; i++) {
    System.out.println(String.format("%07d", Integer.parseInt(Integer.toBinaryString(i))));
}

This will show you :

0000000
0000001
...
...
1111110
1111111
YCF_L
  • 49,027
  • 13
  • 75
  • 115
0

Here is a solution using binary representation:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        for (int i = 0; i < 128; i++) {
            System.out.println(padLeft(Integer.toBinaryString(i), 8));
        }
    }

    // borrowed from http://stackoverflow.com/questions/388461/how-can-i-pad-a-string-in-java
    public static String padLeft(String s, int n) {
        return String.format("%1$" + n + "s", s).replace(' ', '0');  
    }
}

demo