You need to sign in to do that
Don't have an account?

Create an Apex class with a method that returns a list of strings
Hello all,
i am trying to pass this trailhead code challenge.
Can someone please explain why this code1 is incorrect and code2 is correct.
code1
public class StringArrayTest {
public static string[] generateStringArray()
{
list <string> name= new list <string>();
integer i;
integer n=3;
for(i=0;i<=n;i++){
name.add('Test' +' '+ i);
system.debug(name[i]);
}
return name;
}
}
code2
public class StringArrayTest {
public static String[] generateStringArray(integer len) {
String[] myArray = new List<String>();
for(Integer i=0;i< len;i++) {
myArray.add('Test ' +i);
System.debug(myArray[i]);
}
return myArray;
}
}
I tried executing your code 1 in the dev console , it is working fine . Maybe as you have predefined the integer limit to 3 , all the test cases in trailhead is not passing and thats why it is showing incorrect .
Whreas in code 2 , the limit is defined in the method , passing it in run time and it executes for all the limit defined during it and passing all the test cases.
Like a general scenario it will pass all test cases.
It it helps , please mark this as Best Answer.
Thank you .
public static List<String> generateStringArray() {
List<String> name = new List<String>();
for (Integer i = 0; i < 3; i++) {
name.add('Test ' + i);
System.debug(name[i]);
}
return name;
}
}