[java] Need help printing an array.

Started by
5 comments, last by FlaiseSaffron 14 years, 1 month ago
I am trying to return an array and have it print. The correct output should be [0 , 5] , however it comes out as "[I@138c63" Any ideas? Thanks.
Advertisement
Need more info.What does [0,5] mean? Is the elements in the array or something else? If it is the members of the array then this should work.Keep in mind that the array is passed to the method by a pointer so the changes you make in the function are actually made on the array you declare outside.Also passing in NULL or an array with one element will cause nasty behaviour :)

#include <iostream>void changeArray(int *array){	array[0] = 0;	array[1] = 5;}int main(){	int arr[2] = {0,0};	changeArray(arr);	std::cout << "["<<arr[0] <<","<<arr[1]<<"]";	return 0;}
What I have to do is call the method from the main constructor like so:

"System.out.println(findAll(a,7)); //outputs [0, 5]"

And inside the method findAll() I have to return the actual array so it will print from the previous println command.

"return hita;"

hita being an array containing 0 in index 0 and 5 in index 1.

Ive tried everything I can think of and it just keeps printing that nonsense string of characters.
Can you post a little more code? The findAll method and the lines before calling the method so we can see what a contains before being passed to the method.
    public int[] findAll(int a[], int elem2)    {        int count = 0, hits = 0, count2 = 0;                for ( int e : a )        {            if ( e == elem2 )            {                hits++;            }        }                int[] hita = new int[hits];                            for ( int f : a )        {            if ( f == elem2 )            {                hita[count2] = count;                count2++;            }            count++;        }                return hita;    }}


Sorry, cant figure out how to show code in the box. This is probably the fourth time Ive completely redone this method with entirely different loops and statements, and it still prints the random characters.
Ok, I figured out I have to write a different method that does what you first posted, thanks :)
The functionality you're looking for is already in the standard library.

int[] array = ...;System.out.println(java.util.Arrays.toString(array));

This topic is closed to new replies.

Advertisement