从文件中读取String和Int,然后循环遍历?

时间:2019-05-01 12:40:30

标签: java

我正在尝试获取它,以便当它读取文件时,它将逗号前的所有内容都拆分为一个元素,然后由于有10个整数等级,因此需要将这些等级解析为一个int,然后针对平均。但是,我不确定如何实际完成此操作。我一直在寻找解决方案达数小时之久,但似乎还是无法解决。我真的很感谢这里的帮助,因为我目前的脑细胞用完了。 谢谢,-从刚接触编程的人开始。

作业: https://i.stack.imgur.com/L7E9x.png

我从中读取的.txt文件: https://i.stack.imgur.com/nxCi4.png

我当前的代码:

public class Main {

    public static void main(String[] args) throws IOException {

        Scanner scanner = new Scanner(System.in);
        String userInput;
        System.out.println("Enter raw grades filename:");
        userInput = scanner.nextLine();

        BufferedReader br = new BufferedReader(new FileReader(userInput));

        String line = "";
        String txtSplitBy = ", ";

        while ((line = br.readLine()) != null) {

        String[] splitLine = line.split(", ");
        String name = splitLine[0];
        String scores = splitLine[2];

        int i = Integer.parseInt(scores);

        }
    }
}

2 个答案:

答案 0 :(得分:0)

BufferedReader br = new BufferedReader(new FileReader(userInput));

String line;
String txtSplitBy = ",";

while ((line = br.readLine()) != null) {
    int score = 0;
    String grade;
    String[] splitLine = line.split(txtSplitBy);
    String name = splitLine[0];
    for ( int i =1; i <= 10; i++) {
        score += Integer.parseInt(splitLine[i]);
    }
    if ( score < 50 ) {
        grade = "B";
    }else if ( score < 60 ) {
        grade = "A";
    }else {
        grade = "S";
    }
    System.out.println(name +"," + (score/10) + "," + grade );
}

您需要在此处添加成绩逻辑。

答案 1 :(得分:0)

这是我的版本,我保持简单,毕竟这是您的作业!

public static void main(String[] args) throws IOException {
    Scanner scanner = new Scanner(System.in);
    String userInput;
    System.out.println("Enter raw grades filename:");
    userInput = scanner.nextLine();

    BufferedReader br = new BufferedReader(new FileReader(userInput));

    String line = "";
    String txtSplitBy = ","; // Changed from ', ' to ','

    while ((line = br.readLine()) != null) {
        String[] splitLine = line.split(",", 2); // The threee caps the number of splits
        String name = splitLine[0];

        ArrayList<Integer> grades = new ArrayList<>();
        String[] rawGrades = splitLine[1].split(","); // List of grades as string

        for(String rawGrade : rawGrades) {
            grades.add(Integer.parseInt(rawGrade));
        }
    }
}