Issue
I’ve already created the whole code, but i don’t know how to add a String to a String array.
here’s my code:
**CandidateDAO candidatedao = new CandidateDAO();
String fill = null;
CandidateReport[] candidatesReports = candidatedao.getAllCandidates();
String [] newArray = ;
for(int i = 0; i < candidatesReports.length; i++) {
fill = candidatesReports[i].getCandidateId() + ":" + this.calculateGrade(candidatesReports[i]);
}
return newArray;*****
Solution
String [] newArray = ;
This is obviously wrong. To create an array of any type, you need to first instantiate it correctly. To do this, you need to set its size. The reason why you need to set its size is because arrays are allocated in memory in contiguous locations. This means that each index location is right next to another.
String [] newArray = new String[SOME_SIZE];
The SOME_SIZE
is a value based on whatever you need. In your case, you have another array, candidatesReport
, that could be used to determine the size (length) of your given array.
String [] newArray = new String[candiatesReport.length];
Now that is done, you need to set the value in the array.
newArray[i] = ...;
For you, this is done inside the loop…
for(int i = 0; i < candidatesReports.length; i++) {
newArray[i] = candidatesReports[i].getCandidateId() + ":" + this.calculateGrade(candidatesReports[i]);
}
UPDATE:
This problem is mainly to display some information contained in an array of CandidateReport
objects by collecting data from each instance and concatenating it as a String
. Not knowing about the internals of the aforementioned class, I believe this problem is better served by overwriting the Object’s class toString()
method in the CandidateReport
class, so when objects of this type are printed, the output comes the way we want it. Otherwise, every class that wishes to display CandidateReport
contents, it will have to repeat this same code over and over again. So here is a simple case for overriding toString()
method.
public class CandidateReport {
// rest of code omitted
@Override
public String toString() {
return candidateId + ":" + grade;
}
}
If the grade needs to be calculated, you will be better off putting that logic in a utility class where you could call some static method to return the calculation. For example:
return candidateId + ":" + CalculatorUtilities.calculateGrade(grade);
The point of the matter is that each class should override the Object#toString()
method to provide a default string representation of objects of a given type. If you do this, you won’t need the String array at all. But, if you still feel it is necessary to capture this data in an String array, your code will be much simpler because of the overridden toString()
method.
for(int i = 0; i < candidatesReports.length; i++) {
newArray[i] = candidatesReports[i].toString();
}
Answered By – hfontanez
Answer Checked By – Candace Johnson (BugsFixing Volunteer)