java定义一个方法printArray按照格式打印数组中非0的元素例如1023045打印出来应该为12345返回值:无参数:一个数组
以下是一个可能的实现方法:
public class Main {
public static void main(String[] args) {
int[] arr = {1, 0, 2, 3, 0, 4, 5};
printArray(arr);
}
public static void printArray(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
if (i != 0) {
System.out.print(",");
}
System.out.print(arr[i]);
}
}
System.out.println("]");
}
}
输出结果为:
[1,2,3,4,5]
``
原文地址: https://www.cveoy.top/t/topic/hSSE 著作权归作者所有。请勿转载和采集!