Reputation: 207
I need to know how I can insert data inside objects inside an array of objects using my already made Set methods.
i need to know how should i do it through user , i mean JOptionPane input dialog
student[] s = new student[5];
for (int i=1 ; i <= s.length ;i++) {
s[i] = new student(i,"AAA","Ecommerce",0.0);
}
for (int i=1; i<=s.length;i++) {
name = JOptionPane.showInputDialog("Please Write Name for student n " + i);
major = JOptionPane.showInputDialog("Please Write Major for student n " + i);
gpa = Double.parseDouble(JOptionPane.showInputDialog("Please Write GPA for student n " +i));
s[i] = new student(i,name,major,gpa);
}
I tried to do vars here that get data from user by JOptionPane, but it seems that i only use my already made constructor , not the Set methods.
I need to use the methods because it has some validation code inside it.
Any ideas?
Upvotes: 0
Views: 4660
Reputation: 133597
It's not so clear but actually what you want to do is to inizialize a student without adding it to the array until you are sure that fields are correct
Student[] s = new Student[5];
String name, major;
double gpa;
boolean isCorrect = false;
Student currentStudent;
// in your code there is i = 1, is it intended or mistake?
for (int i=0; i <= s.length; i++)
{
currentStudent = new Student();
while (!isCorrect)
{
name = JOptionPane.showInputDialog("Please Write Name for student n " + i);
isCorrect = currentStudent.setName(name);
if (!isCorrect)
JOptionPane.showMessageDialog(null, "Errors in validating name!");
}
isCorrect = false;
while (!isCorrect)
{
major = JOptionPane.showInputDialog("Please Write Major for student n " + i);
isCorrect = currentStudent.setMajor(major);
if (!isCorrect)
JOptionPane.showMessageDialog(null, "Errors in validating major!");
}
isCorrect = false
while (!isCorrect)
{
gpa = Double.parseDouble(JOptionPane.showInputDialog("Please Write GPA for student n " +i));
isCorrect = currentStudent.setGPA(gpa);
if (!isCorrect)
JOptionPane.showMessageDialog(null, "Errors in validating GPA!");
}
s[i] = currentStudent;
}
This approach will keep asking the user the same field until it's correct.. of course your setters will need to return a boolean that is false
if validation failed.
Upvotes: 1
Reputation: 18861
Don't use values as constructor parameters.
Use only implicit constructor that will allocate memory. As for set methods, write them like :
public void setName(String name) { this.name = name; }
In this set methods do your validation code. Your class needs to have private attiributes, which are exact same as your constructor parameters.
Then change line s[i]=new student(i,name,major,gpa);
with
s[i] = new Student();
s[i].setNumber(i);
s[i].setName(name);
s[i].setMajor(major);
s[i].setGpa(gpa);
I hope this is what you meant
Edit : Or continue using constructors and do validaing with parameters BEFORE you make new instance of Student
Upvotes: 2