Java: how to print an entire array of strings?

偶尔善良 提交于 2021-02-04 21:57:27

问题


I'm trying to print an array of seven strings, and am using a get method to return them to the min before printing, but whenever I run it some random gibberish shows up on the console: [Ljava.lang.String;@6d6de4e1

Here is my get method

String[] getStuff(){
    return stuff;
}

And here is the print method from the main class:

System.out.println(trex.getStuff());

The array is completely valid and full of Strings, so I'm not sure what this error is.


回答1:


You want to print the string values of the interior objects, not the string value of the array. Luckily java has a builtin for this: Arrays.deepToString()

So your print code should be:

System.out.println(Arrays.deepToString(trex.getStuff()));



回答2:


You are printing out a reference to the seven strings and not not the 7 strings. To print out the String either use a for loop

for (String str : array) {
    System.out.println(str);
}

or use the static Array method Arrays.toString(array);




回答3:


You can use the Arrays.toString() static helper method as follows:

System.out.println(java.util.Arrays.toString(trex.getStuff()));



回答4:


You are attempting to print a list.

Instead, try iterating over each element in the list via a for loop.

for(String str : trex.getStuff()) System.out.println(str);



回答5:


You can always make use of the Arrays.toString(String[]). Import java.util.Arrays;

Otherwise, you can iterate over the returned array. What you're seeing is the address of memory where the array starts, rather than its elements.




回答6:


you need to do a for loop and print out each item in the array. For example:

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


来源:https://stackoverflow.com/questions/21616534/java-how-to-print-an-entire-array-of-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!