Home > DeveloperSection > Forums > Converting a text file to an array in Java
Pravesh Singh

Total Post:411

Points:2881
Posted on    December-29-2014 11:12 PM

 Java Java  File  Array 
Ratings:


 1 Reply(s)
 680  View(s)
Rate this:
I'm a beginner at Java and have a list of 25 students that include their name, age, income and IQ in a text file. I'm struggling with how to take this text file and put it in an Array so that I can sort them and such. So far I have:

File myFile = new File ("./src/Project2/StudentList");
Scanner myScan = new Scanner(myFile);

while (myScan.hasNext()) {

    String line = myScan.nextLine();
    Scanner scanner = new Scanner(line);
    scanner.useDelimiter(",");

    while (scanner.hasNext()) {
        String name = scanner.next();
        String age = scanner.next();
        String income = scanner.next();
        String smart = scanner.next();

        Student students = new Student(name, age, income, smart);


        System.out.println(students);
    }
}
I just want to know the easiest way to go about this. I'm so close, I can feel it! Thanks in advance.


Royce Roy
Royce Roy

Total Post:134

Points:938
Posted on    December-30-2014 1:01 AM

Define your array:

Student[] students = new Student[25];
int i = 0;
then in your loop

Student student = new Student(name, age, income, smart);
students[i++] = student;
or dynamic array

List<Student> students = new ArrayList()<>;
and in loop:

Student student = new Student(name, age, income, smart);
students.add(student);

Don't want to miss updates? Please click the below button!

Follow MindStick