如何使用方法计算文本文件的总和?

问题描述 投票:0回答:1

代码是: 编辑:我只能为这个作业做一个方法。我不允许创建将为我的课程提交的测试课程。

假设文本文件内容为:11 3 6 9 10 7

//Problem 1: Sum of all numbers in a line
public int Problem1(File file) throws FileNotFoundException{ 
    
    try {
        // Normal
        File outFile = new File("Problem1.txt");
        FileOutputStream outFileStream = new FileOutputStream(outFile);
        PrintWriter pw = new PrintWriter(outFileStream);

        pw.println("Hello World");

        pw.close();
        
    } catch (FileNotFoundException e) {
    }
    int sum =0;
    try {
        Scanner input = new Scanner(new File("Problem1.txt"));
        while(input.hasNextInt()) {
            int num = Integer.parseInt("Problem1.txt");
            sum+=num;
        }
    }
    catch (FileNotFoundException e) {
    System.out.println("File Not Found.");
    }
    return sum;
}

说实话,100% 不确定我在做什么。我所知道的是,我尝试输出文件并通过 while 循环运行它以获得总和。

java methods text-files
1个回答
0
投票

我会创建一个带有两个参数的方法,输入文件名和输出文件名。然后我会创建另一个方法来加载文件、对值求和并返回结果。然后,您可以在写入输出文件时调用此方法。

以下不带参数的程序应生成一个包含值

46
.

的文件
import java.io.*;
import java.util.*;

public class Problem {
    public static void main(String[] args) {
        if (args.length == 2) {
            process(args[0], args[1]);
        } else {
            process("Problem1.txt", "Problem1_Answer.txt");
        }
    }

    public static void process(String inputFilename, String outputFilename) {
        try {
            FileWriter writer = new FileWriter(outputFilename);
            writer.write(Integer.toString(sumOfIntegers(inputFilename)));
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static int sumOfIntegers(String inputFilename) {
        Scanner scanner = null;
        int sum = 0;
        try {
            scanner = new Scanner(new File(inputFilename));
            while (scanner.hasNextInt()) {
                sum += scanner.nextInt();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
        return sum;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.