I have a for loop and I want to add strings to a string array inside that loop.
String[] result = new String[5]; for(int i=0; i<this.registration.length; ++i){ //need to start from index 1 for some calculation String stringResult = String.format("%s(%s)", this.registration[i].getMarks(), this.registration[i].getGrade()); result = new String(){stringResult}; } System.out.println(Arrays.toString(result));
How can I achieve that? The output should look like this-
{100(A), 70(B), 0(F)}
Advertisement
Answer
You can create the result
array with a size that matches the registration
array length, since you know you want to create one result for each registration
entry. You then can loop over the registration
array, build the stringResult
for a given index, and assign it to the corresponding index of the result
array.
String[] result = new String[this.registration.length]; for (int i = 0; i < this.registration.length; ++i) { String stringResult = String.format("%s(%s)", this.registration[i].getMarks(), this.registration[i].getGrade()); result[i] = stringResult; } System.out.println(Arrays.toString(result));