Java arrays printing out weird numbers and text [d

2018-12-31 05:31发布

This question already has an answer here:

I'm new to programming. I'm sure the answer for this question is out there, but I have no idea what to search for.

Ok, I'll go right to it.

Here's my code:

int[] arr;
arr = new int[5];

arr[0] = 20;
arr[1] = 50;
arr[2] = 40;
arr[3] = 60;
arr[4] = 100;

System.out.println(arr);

This compiles and works fine. It's just the output from CMD that I'm dizzy about.

This is the output: [I@3e25a5.

I want the output to represent the exact same numbers from the list (arr) instead. How do I make that happen?

10条回答
骚的不知所云
2楼-- · 2018-12-31 06:08
System.out.println(Arrays.toString(arr));

The current output is classtype@hashcode.

Incase you need to print arrays with more than one dimension use:

Arrays.deepToString(arr);

Also remember to override toString() method for user-defined classes so that you get a representation of the objet as you choose and not the default represention which is classtype@hashcode

查看更多
与君花间醉酒
3楼-- · 2018-12-31 06:09
for (int i = 0; i < arr.length; ++i)
{
  System.out.println(arr[i]);
}
查看更多
临风纵饮
4楼-- · 2018-12-31 06:11

My version of a shorter!

Use Arrays.toString() and PrintStream.printf(String format, Object... args).

System.out.printf("%s%n", Arrays.toString(arr));
查看更多
零度萤火
5楼-- · 2018-12-31 06:19

It prints it's .toString() method you should print each element

for(int i=0; i<arr.length; i++) {
   System.out.println(arr[i]);
}

or

for(Integer i : arr) {
  System.out.println(i);
}
查看更多
登录 后发表回答