Printing array shows wrong output

前端 未结 3 795
感动是毒
感动是毒 2021-01-27 22:36

What is wrong with this code I\'m getting wrong output. I don\'t know what\'s wrong, I hope you could help me:

public class Main{
  public static void main(Strin         


        
3条回答
  •  臣服心动
    2021-01-27 22:48

    data is an array of ints. You should use Arrays#toString(), which is implemented this way:

    3860     public static String toString(int[] a) { {
    3861        if (a == null)
    3862            return "null";
    3863        int iMax = a.length - 1;
    3864        if (iMax == -1)
    3865            return "[]";
    3866
    3867        StringBuilder b = new StringBuilder();
    3868        b.append('[');
    3869        for (int i = 0; ; i++) {
    3870            b.append(a[i]);
    3871            if (i == iMax)
    3872                return b.append(']').toString();
    3873            b.append(", ");
    3874        }
    3875    }
    

    Make sure that you understand it, it will help you to understand arrays.

    You can loop on the array and manually print it:

    for(int i: data) {
        System.out.println(i + " ");
    }
    

    This way you have control on which values to print, e.g. even values:

    for(int i: data) {
        if(i % 2 == 0) {
            System.out.println(i + " ");
        }
    }
    

    Regarding the output you are getting, this is the explanation about it:

    In Java, each object has toString() method, the default is displaying the class name representation, then adding @ and then the hashcode.

提交回复
热议问题