用Java方法打印数组

时间:2015-09-09 17:16:25

标签: java

所以我需要将一个整数数组打印到一个String中,我几乎没有问题

public static String arrayToString(int[] anArray) {
    String x = "";
    String y = "";
    String result = "";
    for (int i = 0; i < anArray.length; i++) {
        y = Integer.toString(anArray[i]);
        x = x + ", " + y;
    }
    result = "[" + x + "]";
    return result;
}

public static void main(String[] args) {
    int arrayInt[] = new int[] { 80, 100, 80, 92, 95, 87, 82, 76, 45, 76, 80, 70};
    System.out.println("array : " + arrayToString(arrayInt));
}

当我执行代码时,而不是打印:

  

[80,100,80,92,95,87,82,76,45,76,80,70]

我明白了:

  

[,80,100,80,92,95,87,82,76,45,76,80,70]

这应该对我来说非常简单,但是我被卡住了,我需要在哪里删除异常?

5 个答案:

答案 0 :(得分:0)

您只是在开头添加额外的,。摆脱它的一个简单方法是,
取代

result = "[" + x + "]";

result = "[" + x.substring(1) + "]";

但最好的解决方案是使用Arrays.toString。有关详细信息,请参阅this

答案 1 :(得分:0)

问题在于您在开头时收到了额外逗号 ,。这将解决您在arrayToString函数中的问题:

public static String arrayToString(int[] anArray) {
    String x = "";
    String y = "";
    String result = "";
    for (int i = 0; i < anArray.length-1; i++) {
        y = Integer.toString(anArray[i]);
        x = x + y + ",";
    }
    y = Integer.toString(anArray[anArray.length-1]);
    x = x + y;
    result = "[" + x + "]";
    return result;
}

答案 2 :(得分:0)

 public static String arrayToString(int[] anArray) {
    String x = "";
    String y = "";
    String result = "";
    for (int i = 0; i < anArray.length; i++) {
        y = Integer.toString(anArray[i]);
        if(x.isEmpty()){
            x = y;
        } else {
            x = x + ", " + y;
        }
    }
    result = "[" + x + "]";
    return result;
}

public static void main(String[] args) {
    int arrayInt[] = new int[] { 80, 100, 80, 92, 95, 87, 82, 76, 45, 76, 80, 70 };
    System.out.println("array : " + arrayToString(arrayInt));
}

答案 3 :(得分:0)

您可以检查第一个元素。

if( i == 0 ) x = y; else x = x + ", " + y;

答案 4 :(得分:-1)

请更改代码中的最后一行,结果字符串变量如下:

public static String arrayToString(int[] anArray) {
String x = "";
String y = "";
String result = "";
for (int i = 0; i < anArray.length; i++) {
    y = Integer.toString(anArray[i]);
    x = x + ", " + y;
}
 result = "[" + x + "]";
 return result.charAt(0)+result.substring(3);
}