Home > Software engineering >  Add strings to an array of strings inside for loop using java
Add strings to an array of strings inside for loop using java

Time:03-19

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)}

CodePudding user response:

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));
  • Related