java存储从文件到数组的整数输入

时间:2018-02-28 10:52:40

标签: java arrays integer java.util.scanner

考虑我有一个带有如下数字的文件 - 文件的名称是 seminar.txt。这个文件是我收集的学生数量的数据集 在1月至3月期间参加了我的研讨会。其中一些数据是 文本。你的任务是只提取学生人数并计算和显示 在三个月内参加研讨会的学生总数。叫这个 程序Seminar.java

January
Week 1 23
Week 2 30
Week 3 20
Week 4 40
February
Week 1 20
Week 2 19
Week 3 19
Week 4 20
March
Week 1 10
Week 2 50
Week 3 21
Week 4 20

1 个答案:

答案 0 :(得分:1)

package com.satya.prakash.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Seminar {

    static String filePath = "D:\\seminar.txt";

    public static void main(String[] args) throws IOException {
        File f = new File(filePath);

        if (f.exists()) {
            BufferedReader br = new BufferedReader(new FileReader(f));

            String str;
            StringBuilder text = new StringBuilder();
            while ((str = br.readLine()) != null) {
                text.append(str);
            }
            String strArray[] = text.toString().replace("January", "").replace("February","").replace("March", "").replace("Week","").trim().split(" ");

            boolean flag=false;
            Integer sum=0;
            for(String s :strArray) {
                if(flag) {
                    try {
                        sum= sum + Integer.parseInt(s);
                    }catch(Exception e) {}
                    flag=false;
                }else
                    flag=true;
            }
            System.out.println("Total Number of Student : "+sum);

        } else
            System.out.println("File Not Found...");

    }

}

Output : Total Number of Student : 129