0

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);
  }

}
5
  • 1
    Are you sure the platform isn't adding the other set of []? Because that output isn't possible with the code shown. Commented Apr 16, 2018 at 17:48
  • @Kayaman I guess that may be possible, though I've done tons of these tasks on codewars and so far their compiler hasn't changed the type of output Commented Apr 16, 2018 at 17:55
  • I could not reproduce it: ideone.com/dvhGW0. How are you sure the output is "[[1, 2, 3, 4]]"? I get "[1, 2, 3, 4]". Commented Apr 16, 2018 at 17:55
  • 1
    Please post a Minimal, Complete, and Verifiable Example. Commented Apr 16, 2018 at 17:56
  • @lexicore I'm sure the output is [[1, 2, 3, 4]] because when I "attempt" the task (tell the site I want to run the code and see if I get the expected answer) it says: expected:<[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]> but was:<[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]> Commented Apr 16, 2018 at 18:01

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Aha, this makes sense. But how would I go about returning the values in the array without returning the array itself? probably a noob question but im not great at Java :[
this worked! thank you so much. very easy to understand once you made me realize it just wanted to strings alone :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.