如何在java中的循环中创建新对象?
我有一个名为“info”的字符串数组列表,每个字符串都包含关于我班学生的一个实例的信息。 我尝试将Arraylist转换为数组,然后使用split方法对其进行解析如何在java中的循环中创建新对象?,java,loops,object,Java,Loops,Object,我有一个名为“info”的字符串数组列表,每个字符串都包含关于我班学生的一个实例的信息。 我尝试将Arraylist转换为数组,然后使用split方法对其进行解析 String[] Stringinfo = new String[info.size()]; Stringinfo = info.toArray(Stringinfo); 解析每一行之后,我尝试在for循环中创建一个新对象,并将其添加到Students ArrayList。每次我创建这个新对象Student时,之前添加到Studen
String[] Stringinfo = new String[info.size()];
Stringinfo = info.toArray(Stringinfo);
解析每一行之后,我尝试在for循环中创建一个新对象,并将其添加到Students ArrayList。每次我创建这个新对象Student时,之前添加到Students ArrayList的其他对象都会更改为这个新对象
String[] temp;
for(int i = 1; i < LineCount + 1 ; i++)
{
temp = Stringinfo[i].split(" ");
Student s = new Student(Integer.parseInt(temp[0]), Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), Integer.parseInt(temp[4]));
Students.add(s);
}
我找了很多,但找不到答案。很抱歉,如果答案很明显,我是Java新手。
任何帮助都将不胜感激。
提前谢谢
编辑:
将单词
static
从Student
课堂中去掉
static
表示“所有学生都可以选择其中一个”。但是每个学生都应该有不同的年龄、id等,因此这些字段(以及相关的方法)不应该是静态的。静态成员意味着该成员属于类而不是对象,因此您的成员会不断变化
我猜你们的成员是静态的,所以试着这样定义你们的学生班级:
public class Student {
private int certification_num;
private int class_id;
private int average_point;
private int student_id;
private int age;
public Student(int certif, int clazz, int ave, int i, int a)
{
this.certification_num = certif;
this.class_id = clazz;
this.average_point = ave;
this.student_id = i;
this.age = a;
}
}
首先,我建议你改变你的学生课程如下:
public class Student
{
private int certification_num;
private int class_id;
private int average_point;
private int student_id;
private int age;
public int getCertification_num() {
return this.certification_num;
}
// Do this for all variables
public void setCertification_num(int certif) {
this.certification_num = certif;
}
// Do this for all variables
}
之后,你可以轻松地使用你的学生课程。在其他情况下,当您没有或不需要所有信息时
填充阵列:
ArrayList<Student> students = new ArrayList<Student>();
for(int i = 1; i < LineCount + 1 ; i++)
{
String[] temp;
temp = Stringinfo[i].split(" ");
Student s = new Student();
s.setCertification_num(Integer.parseInt(temp[0]);
//Do for all other fields
Students.add(s);
}
ArrayList students=new ArrayList();
对于(int i=1;i
你能发布更多的学生类吗?我猜这些字段是静态的…你的学生构造函数的文件不会编译,因为类
不能用作变量名。请不要以大写字符开头变量名。这不是你的真实代码。你有一个名为类的变量ordstatic
从你的Student
类中删除。@Steven是对的。你将所有成员声明为static(这意味着无论你创建多少个Student类,该字段都只有一个副本)。谢谢你的帮助!!我不知道…:)这正是我的问题。非常感谢你的帮助!
public class Student
{
private int certification_num;
private int class_id;
private int average_point;
private int student_id;
private int age;
public int getCertification_num() {
return this.certification_num;
}
// Do this for all variables
public void setCertification_num(int certif) {
this.certification_num = certif;
}
// Do this for all variables
}
ArrayList<Student> students = new ArrayList<Student>();
for(int i = 1; i < LineCount + 1 ; i++)
{
String[] temp;
temp = Stringinfo[i].split(" ");
Student s = new Student();
s.setCertification_num(Integer.parseInt(temp[0]);
//Do for all other fields
Students.add(s);
}