+ Start a Discussion
BijaySBijayS 

Getting Error while submitting the challenge for Apex

I am not sure whats the issue or i misunderstood the problem statement :

User-added image

my code :

public class StringArrayTest {
    public static List<String> generateStringArray(Integer num) {
        List<String> generateString = new List<String>();
        
        for(Integer i = 0; i <= num ; i++) {
            string formattedString = 'Test ' + i;
            generateString.add(formattedString);
        }
        System.debug(LoggingLevel.INFO, 'Formatted String for Trail Head'+generateString);
        return generateString;
    }
}

Could anyone help me understand the issue even though its silly :)
Amit Chaudhary 8Amit Chaudhary 8
Please check below post. I hope that will help you
https://developer.salesforce.com/forums/ForumsMain?id=906F0000000AvPBIA0

Please try below code.
public class StringArrayTest {
    
    public static List<String> generateStringArray(Integer n)
    {
        List<String> myArray = new List<String>();
        for(Integer i=0;i<n;i++)
        {
           myArray.add('Test '+i);
           System.debug(myArray[i]);
        }
        return myArray;
    }
}

Please let us know if this will help you

Thanks
Amit Chaudhary
 
James LoghryJames Loghry
Simply put, your array is returning 1 more record than it should be, because your loop operates over i <= num instead of just i < num.
BijaySBijayS
Thanks Amit and James for pointing out the silly mistake.