简体   繁体   English

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

[英]How to store a text file into arrays

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. 大家好,基本上,我有一个“ classroom.txt”文件,其中包含教授的名字以及第一行的房间容纳人数和实际人数。 After the first line is the name of the students, male or female, ID number, and age. 第一行之后是学生的姓名,男女不限,身份证号和年龄。 IE 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. 基本上,我想将50、25岁的John Doe存储在“教师列表”中,其余的存储在学生列表中。

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

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: 在循环中,您可以继续阅读并添加到学生的ArrayList中:

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

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

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代表您到目前为止已经读了多少行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM