Home > OS >  adding to String array from start position in different array (java)
adding to String array from start position in different array (java)

Time:12-24

I'm trying to output an array starting using the parameters given in the methods. Essentially the results printed should be;

{"sat", "on"}
{"the", "mat"}
{"sat", "on", "the"}

but im struggling to understand why the output im getting is:

[Ljava.lang.String;@57829d67

as it seemingly should work.

public static void main(String[] args) {
    String[] data = {"the", "cat", "sat", "on", "the", "mat"};
    System.out.println(pagedData(data, 2, 2));
    System.out.println(pagedData(data, 4, 4));
    System.out.println(pagedData(data, 2, 3));
}
public static String[] pagedData (String[] list, int start, int end){
    String[] output = new String[end];
    int x = 0;
    for (int i = 0; i < end; i  ) {
        output[x] = list[start];
        x  ;
    }
    return output;
}

CodePudding user response:

Because you're printing out the array itself. When an array is converted to a string (which happens when you try to print it), it'll display that mess (whcih for our purposes does not need to be explained). You need to print out the individual elements of the array, for example:

 System.out.println(pagedData(data, 2, 2)[0]);

Prints the first element of the array.

CodePudding user response:

If you want to print all the elements in an array then use Arrays.toString(_your_array_var); method.

For Eg.

System.out.println(Arrays.toString(pagedData(data, 2, 2)));

Else, if you want to print each element in an array use a for loop or enhanced for loop and print each element with space seperated in a single line.

String[] array_A = pagedData(data, 2, 2);
for (String s: array_A) {
System.out.print(s   "\n");
}
  • Related