'How to split input text file that has string and doubles?

I am to read from an .txt input and sort into array by line (read: first name, last name, grade1, grade 2, grade3) but I am having issues. I am assuming that I would have to create arrays for each person, but I cannot get past sorting each line entry. I understand basics about how to use split, but I assume that I will have to use nested for loops to separate strings from doubles and have each in its own array. I am not sure about how to compile this.



Solution 1:[1]

You can use a FileReader to read line-by-line. You can then split the resulting string on the comma, and use Double.valueOf to get your values. The following example is simple, but will assume the file is correctly formed:

public class Test {

    static class Student {
        private String firstName;
        private String lastName;
        private double math;
        private double english;
        private double computerScience;

        public Student(String firstName, String lastName, double math,
                double english, double computerScience) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.math = math;
            this.english = english;
            this.computerScience = computerScience;
        }

        @Override
        public String toString() {
            return "Name: " + firstName + " " + lastName + ", Math: " + math +
            ", English: " + english + ", Computer Science: " + computerScience;
        }
    }

    public static void main(String[] args) {
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader("/home/username/grades.txt"));
            String line = reader.readLine();
            while (line != null) {
                String[] gradeArray = line.split(",");
                Student myStudent = new Student(gradeArray[0], gradeArray[1],
                        Double.valueOf(gradeArray[2]), Double.valueOf(gradeArray[3]),
                        Double.valueOf(gradeArray[4]));

                System.out.println(myStudent.toString());
                line = reader.readLine();
            }
        }
        catch (NumberFormatException|IndexOutOfBoundsException badFile) {
            System.out.println("You have a malformed gradebook");
            badFile.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Agricola