尝试在阵列打印机中添加逗号

时间:2016-11-16 03:44:30

标签: java arrays

我认为我的问题在if和else语句中。程序需要打印数组,其间有逗号和括号。是否需要添加其他内容?我很新,所以我很确定解决方案很简单。感谢

public class array {

public static void main(String[] args) {

int[] oneD = {5 ,6 ,7 ,8};

int[][] twoD ={{2,4,6,8},{8,7,9,1},{3,5,1,2}};

int[][] twoD2 = {{1,2},{3,4,5},{6},{7,8,9}};

printArray(oneD);
printArray(twoD);
printArray(twoD2);



}

public static void printArray(int[] arr) {

System.out.print("[");  

for (int i = 0; i < arr.length; i++)

{

if (i < arr.length-1)
System.out.print(arr[i]);

else 
System.out.print(arr[i] + ",");

} 

System.out.print("]");
}




public static void printArray(int[] [] arr) {

System.out.print("[");

for (int i = 0; i < arr.length; i++)

printArray(arr[i]);

System.out.print("]");

}

}

3 个答案:

答案 0 :(得分:0)

您需要交换条件:

if (i < arr.length - 1)    
    System.out.print(arr[i] + ",");    
else
    System.out.print(arr[i]);

答案 1 :(得分:0)

它处于if状态,

if (i != arr.length-1)
    System.out.print(arr[i] + ",");
else 
    System.out.print(arr[i]);

如果索引不在最后一个元素打印&#39; a [i],&#39; 否则打印&#39; a [i]&#39;。

更有道理吗?

答案 2 :(得分:0)

  public static void printArray(int[] arr) {

   System.out.print("[");

    for (int i = 0; i < arr.length; i++)

    {  System.out.print(arr[i]);

        if (i < arr.length-1)
            System.out.print( ",");

    }

    System.out.print("],");

}