function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sai Anudeep MeelaSai Anudeep Meela 

Trying to complete a challange

Challange : Create an Apex class that returns an array (or list) of formatted strings ('Test 0', 'Test 1', ...). The length of the array is determined by an integer parameter.The Apex class must be called 'StringArrayTest' and be in the public scope.
The Apex class must have a public static method called 'generateStringArray'.
The 'generateStringArray' method must return an array (or list) of strings. Each string must have a value in the format 'Test n' where n is the index of the current string in the array. The number of returned strings is specified by the integer parameter to the 'generateStringArray' method.

And this is the code I have written :

public class StringArrayTest {

    public static String[] generateStringArray(Integer arraynum){
        String[] returndata = new String[arraynum];
           String value = 'Test ';
        returndata.clear();
        for(Integer i=0;i<=arraynum;i++) {
             returndata.add(value+i);
            System.debug('The output' + returndata);
    }
        return returndata;
}
}

Error :

Challenge not yet complete... here's what's wrong: 
Executing the 'generateStringArray' method failed. Either the method does not exist, is not static, or does not return the proper number of strings.

Not sure what is the mistake done by me in the code, can some one help me out?

Thanks,
Sai
ClintLeeClintLee
Your for-loop has "i <= arrayNum" so your list size is off by one. It should be "i < arrayNum".

Try this:
 
public class StringArrayTest
{
    public static List<String> generateStringArray(Integer num)
    {
        List<String> returnData = new List<String>();

        for(Integer i = 0; i < num; i++)
        {
            returnData.add( 'Test ' + i);
        }

        return returnData;
    }
}

Hope that helps,

Clint
 
Joe GlassJoe Glass
I'm having the same issue.  I basically used the same code suggested by Clint, but still getting the error.

public class StringArrayTest {
    public static List<String> generateStringArray(Integer length)  {
        List<String> testArray = new List<String>();
        for(Integer n=0;n<length;n++) {
            testArray.add('Test ' + n);
            System.debug('The Value is' + testArray[n]);
            return testArray;
        }
    }
}

Thanks!

Joe
Joe GlassJoe Glass
Never mind.  Had the return statement inside the for loop.  This one worked!

public class StringArrayTest {
    public static List<String> generateStringArray(Integer length)  {
        List<String> testArray = new List<String>();
        for(Integer n=0;n<length;n++) {
            testArray.add('Test ' + n);
            System.debug('The Value is' + testArray[n]);
        }
            return testArray;
    }
}

Joe