2017-03-31 49 views
2

所以我試圖創建一個AClass(es)AClass(es)7-switch String參數,其中每個字符都在[1]或關[0],例如: 0011010Java - 通過輸入掩碼xxxxxxx循環所有輸入,其中x = 0或1

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")); 
     */ 
    } 
} 

什麼是創建所有128個唯一參數AClass(es)的最有效方法?

編輯:誤以0000001開工100萬而不是

+0

你不能使用二進制嗎? (有一些聰明的格式,應該這樣做) – 2017-03-31 17:42:32

+0

你可能是對的,我應該能夠弄清楚,以及壞的問題。 – Daedric

回答

3

您可以使用左側Integer.toBinaryString(int i)String.format來完成你的字符串以0:

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

這將告訴你:

0000000 
0000001 
... 
... 
1111110 
1111111 
0

這是一個使用二進制表示的解決方案:

/* 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