Reputation: 331
Hey guys so basically I have a "classroom.txt" file that has the the name of the professor along with the room capacity and actual number of students on the first line. After the first line is the name of the students, male or female, ID number, and age. IE
John Doe, 50, 25
David Clark, M, 100, 17
Betty Johnson, F, 101, 17
Mark Jones, M, 102, 18
basically I want to store John Doe, 50, 25 in an array List of Teachers and the rest in an array list of students.
try{ read = new Scanner(new File("classrom.txt"));
while(read.hasNextLine())
{
//this is where I'm stuck to only read the first line into teacher arraylist
//and the rest into students
}
catch(Exception e)
System.out.println("File Not Found"!);
Upvotes: 0
Views: 57
Reputation: 305
It seems that you are saying you don't know how to tell that the first line is for teachers. The way to do this is to have an int that represents how many lines you have read so far.
int i = 0;
try{ read = new Scanner(new File("classrom.txt"));
while(read.hasNextLine())
{
if (i == 0) {
// do teacher stuff
} else {
// do student stuff
}
i++; //increment i to represent how many lines have been read
}
catch(Exception e)
System.out.println("File Not Found"!);
Upvotes: 0
Reputation: 1567
Try using a counter. if the first line of the text file will ALWAYS contain the Teachers info, then just use a counter for the first line.
try{ read = new Scanner(new File("classrom.txt"));
while(read.hasNextLine())
//this counter will count your lines
int counter = 1;
{
String line = read.readLine()
//if counter is 1, then your String line will contain the teacher's info
if(counter == 1){
// do something with the teacher's info. Parse, perhaps
}else{
// do something with the student's info. Parse, maybe
}
counter++;
}
catch(Exception e)
System.out.println("File Not Found"!);
Upvotes: 0
Reputation: 897
Since only the first line contains the teacher data, read the file once outside the loop. Within the loop, you can continue reading & adding into the student's ArrayList:
if(read.hasNextLine()){
String teacherData = read.nextLine();
teacherArrList.add(teacherData);
}
while(read.hasNextLine()){
String studentData = read.nextLine();
studentArrList.add(studentData);
}
Upvotes: 1