Really confused on how to access just the age of a specific student where all the information of students have been stored in a textfile. I am reading the textfile and storing that info into a student object, just need help on accessing this.
public class Student {
private String lName;
private int idNumber;
private int age;
public Student() {
lName = "";
idNumber = 0;
age = 0;
}
public Student(String l, int i, int a) {
lName = l;
idNumber = i;
age = a;
}
public void setName(String last) {
lName = last;
}
public String getName() {
return lName;
}
public void setIdNum(int num) {
idNumber = num;
}
public int getIdNum() {
return idNumber;
}
public void setAge(int a) {
age = a;
}
public int getAge() {
return age;
}
}
My Text File looks something like this: This info is stored in parallel array lists. I don't quite get how to implement this into an object to pass it into my second contractor method.
Josh 2134 19
Smith 5256 21
Rogers 9248 19
Andrew 7742 20
Here's what I've tried;
public static void main(String[] args) {
String file = "studentData.txt";
Scanner reader = new Scanner(file);
ArrayList<Student> users = readFile(file);
Student s = new Student();
users.add(s);
Scanner input = new Scanner(System.in);
//user enters idNumber to display age
System.out.println("Enter ID Number"); //exception handling to be added
int idNum = input.nextInt();
//this part is where I'm stuck
for(int i = 0; i < users.get(i) i++){
if(idNum == users.get(i)){
users.setAge(i);
}
}
System.out.println(users.getAge());
}
//METHOD FOR READING FILE
public static ArrayList<Student> readFile(String file)throws IOException{
Scanner reader = new Scanner(new File(file));
ArrayList<Student> list = new ArrayList<Student>();//creates ArrayList with student object
reader.nextLine();//skips first line
while(reader.hasNext()){//splits all text in the file into words
String lName = reader.next();
int idNum = reader.nextInt();
int age = reader.nextInt();
Student users = new Student(lName ,idNum, age);
list.add(users);
}
return list;
}//end method
The only way I think of fixing this is to read the file 3 times to store the names, idnum, and ages in seperate arraylists. And then use that separate array list to store the age using ageList.get(i). I beleive that would be super uneccessary??