protected void Method() {
...
while (st.hasMoreTokens()) {
int data = Integer.parseInt(st.nextToken());
person[a] = new Person();
person[a].setID(data);
person[a].setResults(data);
a++;
}
}
In another class file
protected void Person() {
int results[] = new int[5];
...
//getters&setters
public void setResults(int[] results) {
this.results = results;
}
}
The setResults is passing in one value at a time, but the setter is expecting an array, what is a better approach to populate the array in student using setters that only take in one value at a time?
I would recommend using a list for this purpose. But for now, you can use a variable to keep store the index at which the value is inserted in the results array and increment it after each insertion.
protected void Person() {
int results[] = new int[5];
int index = 0; // index to insert at
...
//getters&setters
public void setResults(int result) {
if(index < 5) {
this.results[index] = result;
index++;
}
}
}
Then you can call setResults
like
int data = Integer.parseInt(st.nextToken());
person[a].setResults(data);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.