When I run my program that is getting file input from a text file and then saving this input into an array lists, I cannot print the information. I will attach my Student class which is the type I am using for my array lists. I also will attach the class that contains main. I will include a screenshot of the text file and the output that I am currently getting. My goal is to save each students information into a student object and then put these objects into an array lists. Then display the contents of the array lists. Below is the student class.
public class Student {
public String Name;
public int BirthYear;
public int BirthMonth;
public int BirthDay;
public double GPA;
public Student(String Name,int BirthYear, int BirthMonth, int BirthDay,double GPA)
{
Name = this.Name;
BirthYear = this.BirthYear;
BirthMonth =this.BirthMonth;
BirthDay=this.BirthDay;
GPA=this.GPA;
}
public int Age() {
Calendar c = Calendar.getInstance();
if(c.get(Calendar.MONTH)>BirthMonth) {
return (c.get(Calendar.YEAR)-BirthYear);
}
else if(c.get(Calendar.MONTH)<BirthMonth) {
return (c.get(Calendar.YEAR)-BirthYear)-1;
}
else if(c.get(Calendar.MONTH)==BirthMonth) {
if(c.get(Calendar.DAY_OF_MONTH)>BirthDay) {
return(c.get(Calendar.YEAR)-BirthYear)-1;
}
else {
return(c.get(Calendar.YEAR)-BirthYear);
}
}
else {
return 0;
}
}
}
Below is the main class
public class RunStudent {
public static void main(String[] args) throws FileNotFoundException{
File inputFile = new File("studentData1");
Scanner FileIn = new Scanner(inputFile);
ArrayList<Student> List = new ArrayList<Student>();
FileIn.nextLine();
while(FileIn.hasNextLine()) {
String FName, LName;
FName = FileIn.next();
LName = FileIn.next();
int BirthYear = FileIn.nextInt();
int BirthMonth = FileIn.nextInt();
int BirthDay = FileIn.nextInt();
double GPA = FileIn.nextDouble();
String name = FName + " " + LName;
Student s = new Student(name, BirthYear, BirthMonth, BirthDay, GPA);
List.add(s);
}
FileIn.close();
for(int i=0; i<List.size(); i++) {
System.out.println("Name:" + List.get(i).Name);
System.out.println("Age:" + List.get(i).Age());
System.out.println("GPA: " + List.get(i).GPA);
}
}
}
This is the text file This is a sample output
I also have imported java.util.* and java.io.* but it won't let me include it in the post.
The reason the Student class is not retaining the information you're provided is due to the code within the constructor method.
You are assigning the fields incorrectly.
The this keyword refers to the class instance context, and not the scope context.
Flip these assignments.
Output
Here are some recommendations for your code.
You can obtain a year value by simply subtracting the Calendar values.
Or, use a Period object.
Store your fractional values—i.e., GPA—as String or BigDecimal objects.
Additionally, I would use a String#split on each line over a Scanner#next call.