如何将文本文件存储到数组中

时间:2015-02-23 01:58:32

标签: java arrays arraylist

嘿伙计们基本上我有一个" classroom.txt"具有教授姓名的文件以及第一行的房间容量和实际学生数。在第一行之后是学生的姓名,男性或女性,身份证号码和年龄。 IE

John Doe, 50, 25
David Clark, M, 100, 17
Betty Johnson, F, 101, 17
Mark Jones, M, 102, 18

基本上我想将John Doe,50,25存储在教师和教师列表中 其余的在学生名单中。

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"!);

3 个答案:

答案 0 :(得分:1)

由于只有第一行包含教师数据,因此请在循环外读取一次文件。在循环中,您可以继续阅读&添加到学生的ArrayList:

if(read.hasNextLine()){
    String teacherData = read.nextLine();
    teacherArrList.add(teacherData);
}
while(read.hasNextLine()){
    String studentData = read.nextLine();
    studentArrList.add(studentData);
}

答案 1 :(得分:0)

尝试使用计数器。如果文本文件的第一行总是包含教师信息,那么只需使用第一行的计数器。

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"!);

答案 2 :(得分:0)

好像你说你不知道如何判断第一行是给老师的。执行此操作的方法是使用一个int来表示到目前为止已读取的行数。

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"!);