I'm writing a simple Apex class as part of the new Salesforce Trailhead developer course. Here's what I'm trying to do:
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.
Here is my code:
public class StringArrayTest {
//Public Method
public static void generateStringArray(Integer length) {
//Instantiate the list
String[] myArray = new List<String>(length);
//Iterate throught the list
for(Integer i=0;i<myArray.size();i++) {
//Populate the array
myArray.add(myArray[i]);
// Write value to the debug log
System.debug(myArray[i]);
} //end loop
}//end method
}// end class
I'm sure it's something very simple I'm doing wrong. When I execute right now it's returning:
expecting a semi-colon, found ''
Best Answer
You can't instantiate a
List
like that using an integer. You don't need to explicitly specify how much items are going into the list when it is created. Instead, just remove the integer:You're logic in your loop seems to be incorrect as well. Specifically,
myArray
's size will always be 0 when you instantiate it. Change your loop logic to:You want to generate a List of strings based on the
i
variable. You will want to change your internal logic to:Finally, you want to return that Array. You need to change your method so the return type is no longer
void
by changing its signature:then it is just a matter of
return
ing that array at the end of your method:This would bring it all together as:
Some more info on Arrays and Lists, Loops, and Class methods for future reference.