如何分割具有字符串和双精度的输入文本文件?

时间:2019-10-01 02:52:06

标签: java arrays file split line-by-line

我要从.txt输入中读取内容,并按行对数组进行排序(读取:名字,姓氏,等级1,等级2,等级3),但是我遇到了问题。我以为我必须为每个人创建数组,但是我无法对每个行条目进行排序。我了解有关如何使用拆分的基础知识,但我假设我将必须使用嵌套的for循环将字符串与双精度分隔开,并将每个字符串放在自己的数组中。我不确定如何编译它。

1 个答案:

答案 0 :(得分:0)

您可以使用FileReader逐行读取。然后,您可以在逗号上分割结果字符串,并使用Double.valueOf获取值。以下示例很简单,但是将假定文件格式正确:

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();
        }
    }

}