简体   繁体   中英

Printing an array in Java method

So I need to print an array of integers into a String, and I have it almost right with one problem

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));
}

When I execute the code, instead of printing:

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

I get:

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

This should be really simple to me but I'm stuck, where do I need to put an exception to remove it?

You are just adding an extra , in the beginning. One simple way to get rid of it is,
Replace

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

with

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

But the best solution would be to use Arrays.toString . See this for more details.

The problem is that you are getting an extra comma , at the beginning. This will solve your problem in the arrayToString function:

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;
}
 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));
}

您可以包括检查第一个元素。

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

Please change the last line in your code, result string variable as below:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM