(Solved) Array with null (same for Arraylist)
I'm having a problem with calling arrays from a class. I know I should should separate the user interface from the logic so that's what I've tried to do. If you know of a better way please mention that too ;)
Anyway, when ever I use an array list, it always starts with "null". The only fix I've been able to find is by chopping off the first few characters.
This is an example of which the output is:
Quote:
nullname1
name2
name3
name4
name5
Code :
student students = new student();
System.out.println(students.getStudent());
Code :
public class student {
private String student;
public String getStudent() {
String[] students = {"name1","name2","name3","name4","name5"};
for (int i = 0; i < students.length; i++) {
student = student + students[i] + "\n";
}
return student;
}
}
Thanks
Re: Array with null (same for Arraylist)
Write out exactly how your look is working, concentrating on the initial value of the variable student (hint, String is an object which when not instantiated to any value is by default null)
Re: Array with null (same for Arraylist)
You never initially initialized the student string so Java by default assigns it the value of null. Before your for loop, try setting student to the empty string.
Re: Array with null (same for Arraylist)
Changed
to
Code :
private String student = "";
Is this right or have a just done quick fix and missed the point?
Re: Array with null (same for Arraylist)
That works the first time getStudent() is called, but what happens if someone calls getStudent() again?
There's really no reason student should be an object field, move it in as a local variable of getStudent().
Re: Array with null (same for Arraylist)
You're quite right. My solution was poor. I've re-read some principles and am starting again. Thanks for you help :)