繁体   English   中英

如何更改txt文件中的数据(字符串)以便我可以对该数据进行数学运算?

[英]How to change data(string) from a txt file so I can do mathematical operations on that data?

对于我的问题,我看到一个提醒,很多人已经问过这个问题,但我似乎找不到合适的答案。 或者其他编程语言的答案对我没有帮助。 所以我会再问:)

我必须从 txt 文件中读取,然后对数据进行一些数学运算。 这个数据有 10000 行,每行有 20 个数字,用分号隔开。 为了从 txt 文件中读取,我使用了 BufferedReader,它给了我字符串。 我可能必须将此字符串更改为 int。 到现在为止还挺好。 然后我必须把它变成一个数组......如何? 数组需要是二维的还是一维就足够了?

然后最后我必须将结果写入不同的txt文件。 我必须写入可被 3、11 和 5 整除的不同文件编号,然后我必须对 txt 文件中的每一行求和并计算整个 txt 编号的总和。 我到现在为止写的还好吗? 我应该删除一些东西还是?

class Assignment {

    public static void main (String[] args) {

        String nameFile = "numbers.txt";
        String contentFile = readFromFile(nameFile);
        List<Integer> divideNumber = stringToIntList(contentFile);

        List<Integer> divisibleNo = processedData(divideNumber);

        System.out.println(divideNumber);
    }

    private static String readFromFile(String nameFile) {
        String content = "";
        try {
            File file = new File(nameFile);
            BufferedReader read = new BufferedReader(new FileReader(file));

            String line = read.readLine();
            while(line != null) {
                System.out.println(line);
                line = read.readLine();
                content = line;
            }
            read.close();
        } catch (IOException e) {
            System.out.println("There was an error reading from the file");
        }
        return content;
    }

    private static List<Integer> stringToIntList(String contentFile) {
        return Arrays
            .stream(contentFile.split("; "))
            .map(Integer::parseInt)
            .collect(Collectors.toList());
    }

    private static int processedData(int divideNumber) {
        try {
            for(int i = 0; i < divideNumber; i++) {
                if((divideNumber % 3 == 0) || (divideNumber % 5 == 0) || (divideNumber % 11 == 0)) {
                System.out.println(divideNumber);
                }
            }
        }
        catch(NumberFormatException e){
            System.out.println("It is not a number"); 
        }
        return divideNumber;
    }
}

使用带有适当分隔符的扫描仪:

List<Integer> list = new ArrayList<>();
Scanner scanner = new Scanner(new FileInputStream(nameFile))
   .useDelimiter("\\D+");
while (scanner.hasNext()) {
    int i = scanner.nextInt();
    list.add(i);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM