循环创建自定义字符串

时间:2015-10-06 09:37:26

标签: java arrays string

我正在循环将数据写入字符串数组。但我想要的是我创建了另一个循环,我将循环遍历values的数据和amount一样多,但我想对如何这样做有一些指导。

String[] s = new String[20];
String[] values = { "A", "B", "C", "D" };
final int amount = 2;

for (int i = 0; i < s.length; i++) {
    s[i] = String.format("%s%04d", values[0], i); //TODO create another loop?
}
System.out.println(Arrays.toString(s));

首选输出应为:

A0000, A0001, B0002, B0003, C0004, ...

实际输出是:

A0000, A0001, A0002, A0003, A0004, ...

3 个答案:

答案 0 :(得分:2)

  

问题:你的循环错误。

试试这个:

 public static void main(String[] args) {

          int k=0;
          String[] s = new String[20];
            String[] values = { "A", "B", "C", "D" };
            final int amount = 2;
            for (int i = 0; i < values.length; i++){

                 for (int j = 0; j < amount; j++){ //data of values as much as amount
                  s[k++] = String.format("%s%04d", values[i], k); 
                 }
            }
            System.out.println(Arrays.toString(Arrays.copyOf(s,k)));
     }

输出:

[A0001, A0002, B0003, B0004, C0005, C0006, D0007, D0008]

答案 1 :(得分:1)

你需要有2个循环来遍历实际的values数组,然后另一个循环是amount(次数)。

试试这个

    List<String> a = new ArrayList<String>();
    String[] values = { "A", "B", "C", "D" };
    final int amount = 2;
    int incrementVariable = 0;
    for (int i = 0; i < values.length; i++){
        for(int j = 0; j< amount; j++){
            a.add(String.format("%s%04d", values[i], incrementVariable)); 
            incrementVariable +=1;
        }
    }
    System.out.println(a);
}

输出:

[A0000, A0001, B0002, B0003, C0004, C0005, D0006, D0007]

答案 2 :(得分:0)

我喜欢while循环更好:)

String[] s = new String[10];
String[] values = {"A", "B", "C", "D"};
final int amount = 2;

for (int i = 0; i < values.length; ++i) {
    int buffer = 0;
    while(buffer <= amount) {
        int index = i * amount + buffer;
        s[index] = values[i] + String.format("%04d", index);
        buffer++;
    }
}

System.out.println(Arrays.toString(s));
  

[A0000,A0001,B0002,B0003,C0004,C0005,D0006,D0007,D0008,null]