gpt4 book ai didi

java - 循环创建自定义字符串

转载 作者:行者123 更新时间:2023-12-01 22:04:55 25 4
gpt4 key购买 nike

我正在循环将数据写入字符串数组。但我想要的是创建另一个循环,在其中循环遍历 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, ...

最佳答案

Problem : your looping is wrong.

试试这个:

 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]

关于java - 循环创建自定义字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32966588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com