Search code examples
javaarraystry-catchbufferedreaderfilereader

Java - Store data from file into Arrays


I have got my program to read the file and even show the file info but I need to know how to store the data on the file into a two dimensional array and a one dimensional array.

The file that is read looks something like this: 1000,Adams,Olivi,80,78,61,91,20,18,18,20,19,20,19,20,20,19,20,BUS,3.1 1001,Smith,Kimberly,70,68,53,72,20,20,18,20,18,18,20,19,20,19,18,IMD,3.5 1002,Fenandez,Aaron,76,67,72,99,18,20,20,19,19,19,19,19,19,19,20,BIO,2.7

The two dimensional array has to hold all the numbers between the names and the three letters.

The one dimensional array has to hold the GPA at the end.

My question once again is: How would I get the file to store the information into the arrays?

import java.io.*;


public class StudentGrades
{
    public static void main(String[] args)
    {

        int[][] studentScores = new int[93][15];

        float[] studentGPA = new float[93];

        String fileName = "Students.txt";


        try {
            FileReader fileReader = new FileReader(fileName);
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line;

            while((line = bufferedReader.readLine()) != null)
                System.out.println(line);
                }
            catch(IOException ex){
            System.out.println("error");
        }

    }
}

Solution

  • If you are sure that your input from the file will be always in the same form (i.e. with the same amount of data per line, and with this sequence):

    public static void main(String[] args) {
    
            int[][] studentScores = new int[93][15];
    
            float[] studentGPA = new float[93];
    
            String fileName = "Students.txt";
    
            try {
                FileReader fileReader = new FileReader(fileName);
                BufferedReader bufferedReader = new BufferedReader(fileReader);
    
                String line;
    
                int studentIndex = 0;
                String[] lineSplit;
                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println(line);
                    lineSplit = line.split(",");
                    for (int k = 0; k < 15; k++) {
                        studentScores[studentIndex][k] = Integer.parseInt(lineSplit[3 + k]);
                    }
                    studentGPA[studentIndex] = Float.parseFloat(lineSplit[lineSplit.length - 1]);
                    studentIndex++;
                }
            } catch (IOException ex) {
                System.out.println("error");
            }
    
        }