Kevin Lutz
Kevin Lutz

Reputation: 25

Java Array returning as two-dimensional

I'm trying to do a Kata on Codewars in Java that asks "you have decided to write a function that will return the first n elements of the sequence with the given common difference step and first element first." Below I have done what is asked, but when I return the final array it returns as two-dimensional (like [[1, 2, 3, 4]] instead of [1, 2, 3, 4]). Please help me understand why and how to fix this!

import java.util.Arrays;

class Progression {

    public static String arithmeticSequenceElements(int first, int step, 
    long total) {
    int[] intArr;
    intArr = new int [(int)total];
    intArr[0] = first;
    int i = 1;
    while(i<total){
      intArr[i] = intArr[i-1] + step;
      i++;
    }
    return Arrays.toString(intArr);
  }

}

Upvotes: 0

Views: 43

Answers (1)

Kayaman
Kayaman

Reputation: 73558

The platform is expecting you to return just the values 1, 2, 3, 4.

You're returning the default Arrays.toString() representation which is [1, 2, 3, 4]. The platform then displays it as <[[1, 2, 3, 4]]>.

You could return just the elements with for example

String str = Arrays.toString(intArr);
return str.substring(1, str.length()-1);

Upvotes: 1

Related Questions