我需要知道如何使用我已经创建的Set方法在对象数组内的对象中插入数据。
我需要知道我应该如何通过用户,我的意思是JOptionPane输入对话框
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);
}
我试图在这里通过JOptionPane从用户那里获取数据,但似乎我只使用我已经制作的构造函数,而不是Set方法。
我需要使用这些方法,因为它里面有一些验证码。
有什么想法吗?
答案 0 :(得分:2)
不要将值用作构造函数参数。
仅使用将分配内存的隐式构造函数。 至于set方法,请将它们写成:
public void setName(String name) { this.name = name; }
在此设置方法中,执行验证码。您的类需要具有私有属性,这与构造函数参数完全相同。
然后更改line s[i]=new student(i,name,major,gpa);
与
s[i] = new Student();
s[i].setNumber(i);
s[i].setName(name);
s[i].setMajor(major);
s[i].setGpa(gpa);
我希望这就是你的意思
编辑: 或者继续使用构造函数,并在创建Student
的新实例之前使用参数进行验证答案 1 :(得分:1)
目前还不是很清楚,但实际上你想做的是在没有将其添加到数组中的情况下对学生进行初始化,直到你确定字段是正确的
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;
}
这种方法会一直向用户询问相同的字段,直到它正确为止。当然,如果验证失败,你的setter将需要返回一个false
的布尔值。