用 java 实现把{1,2,3,4,5,6,7,8,9,10} 变成{1,2,3,1,2,3,1,2,3,1}
时间: 2023-09-30 19:06:25 浏览: 22
您好,我是ChitGPT,很高兴为您回答问题。针对您的问题,可以通过以下Java代码实现:
```
int[] arr = {1,2,3,4,5,6,7,8,9,10};
int[] res = new int[arr.length];
for(int i = 0; i < arr.length; i++) {
res[i] = arr[i % 3];
}
System.out.println(Arrays.toString(res));
```
解释一下:首先定义一个数组arr存储原有数据{1,2,3,4,5,6,7,8,9,10},另外定义一个数组res存储修改后数据。通过循环将arr中的每个元素取模3,得到0、1、2三个值,用这三个值依次替换res数组中对应的位置元素,得到{1,2,3,1,2,3,1,2,3,1}。最后通过Arrays.toString将数组打印输出。
希望能够解决您的问题,如有其他问题,欢迎继续提问。
相关问题
用 java 实现把{0,1,2,3,4,5,6,7,8,9} 变成{1,2,3,1,2,3,1,2,3,1}
您好,我理解您的问题。以下是Java代码实现将{0,1,2,3,4,5,6,7,8,9}转换为{1,2,3,1,2,3,1,2,3,1}的方法:
```
public static int[] transform(int[] arr) {
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = (i % 3) + 1;
}
return result;
}
public static void main(String[] args) {
int[] arr = {0,1,2,3,4,5,6,7,8,9};
int[] result = transform(arr);
System.out.println(Arrays.toString(result));
}
```
在这个方法中,我们使用了一个简单的循环,对于输入数组中的每个元素,我们计算它在数组中的位置并使用模运算(对于0, 1和2)生成输出数组的对应元素。最后,我们将生成的结果数组返回并将其打印到控制台。
请注意,此代码实现假设输入数组中的元素数量即为10,如果您正在处理一个大小不同的数组,则需要相应地调整代码。
java 如何将String 123456变成 1,2,3,4,5,6
可以使用 StringBuilder 和 for 循环来实现:
```java
String str = "123456";
StringBuilder sb = new StringBuilder(str);
for (int i = sb.length() - 3; i > 0; i -= 3) {
sb.insert(i, ",");
}
String result = sb.toString();
System.out.println(result); // 1,2,3,4,5,6
```
首先将字符串转换成 StringBuilder 对象,然后从后往前每隔三个字符插入一个逗号,最后将 StringBuilder 转换成字符串即可。注意,从后往前插入逗号可以避免插入逗号后对索引造成的影响。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)