+ Start a Discussion
Bhavesh Jain 41Bhavesh Jain 41 

Trailhead challenge:Create an Apex class that returns an array (or list) of strings.

Below is my code:
public class StringArraytest 
{
    public static List<string> generateStringArray(integer n)
    {
        integer i=5;
        List<string> str= new List<string>();
        for(i=0;i<n;i++)
        {
            str.add('test '+i);
            system.debug(str[i]);
        }
        return str;
    }
}

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.
Best Answer chosen by Bhavesh Jain 41
Maharajan CMaharajan C
Hi Bhavesh,

Try the below code:

public class StringArrayTest {

    public static List<String> generateStringArray(Integer length) {
  
        List<String> myArray = new List<String>();
     
        for(Integer i=0;i<length;i++) {
    
            myArray.add('Test ' + i);
         
            System.debug(myArray[i]);
        } 
        return myArray;
    }   
 }

Can you please Let me know if it helps or not!!!

If it helps don't forget to mark this as a best answer!!!


Thanks,
Raj
 

All Answers

Maharajan CMaharajan C
Hi Bhavesh,

Try the below code:

public class StringArrayTest {

    public static List<String> generateStringArray(Integer length) {
  
        List<String> myArray = new List<String>();
     
        for(Integer i=0;i<length;i++) {
    
            myArray.add('Test ' + i);
         
            System.debug(myArray[i]);
        } 
        return myArray;
    }   
 }

Can you please Let me know if it helps or not!!!

If it helps don't forget to mark this as a best answer!!!


Thanks,
Raj
 
This was selected as the best answer
Bhavesh Jain 41Bhavesh Jain 41
hey it worked just curious what was the error I was doing I tried to remove the  integer i=5; and still it did not work. Would appreciate if you could guide me where I was going wrong
Heat26Heat26
@Bhavnesh  You are missing the Capital T in the text  'Test  '+ i and most likely the space between t and quotes. Please try making these changes.
Anubhav Ghosh 17Anubhav Ghosh 17
I have explained this with comments for your understanding
 
public class StringArrayTest 
{  
    //The generateStringArray  function should return a list of Strings|| List<String> and accept an Integer
    public static List<String> generateStringArray(Integer n) //Remember: there is not int in Apex.
    {
        //Create the list that will be returned
        List<String> myList = new List<String>();
        
        //According to the challenge, list should have n items in the form of 'Test n1', 'Test n2' and so on.
        for(Integer i=0; i<n;i++)
        {
            myList.add('Test '+i);
            System.debug('Current String: '+myList.get(i));
        }
        return myList;  
    } 
}