0

次のようなテキストファイルがあります。

1 2 3 4 5

6 7 8 9 1

8 3 9 7 1

9 3 4 8 2

8 7 1 6 5

ここで、各番号はタブで区切られています。

私の質問は、Javaを使用して数値の列を合計する簡単な方法はありますか?1 + 6 + 8 + 9 + 8、2 + 7 + 3 + 3+7などを合計したい。次のコマンドを使用してファイルを読み取っています。

 public static boolean testMagic(String pathName) throws IOException {
    // Open the file
    BufferedReader reader = new BufferedReader(new FileReader(pathName));

    // For each line in the file ...
    String line;
    while ((line = reader.readLine()) != null) {
        // ... sum each column of numbers
        }

    reader.close();
    return isMagic;
}

public static void main(String[] args) throws IOException {
    String[] fileNames = { "MyFile.txt" };

}

4

3 に答える 3

2

列の数は既知ですか、それとも可変ですか? 合計の配列を作成し、各行を int に解析して正しい合計に追加するだけです。

// For each line in the file ...
String line;
int sums[5]; //Change to the number of columns
while ((line = reader.readLine()) != null) {
    String tokens[] = line.split("\t");
    for(int i = 0; i < 5; i++)
    {
       sums[i] += Integer.parseInt(tokens[i]);
    }
 }

事前に列数がわからない場合は、 を使用ArrayListし、最初の行を別の方法で実行して、列数を把握できるようにします。

于 2013-01-26T19:48:29.830 に答える
1

while-loop で、文字列を ( で区切って) 分割し、値\tを解析しintます。

于 2013-01-26T19:45:22.050 に答える
1

テキスト ファイルから数値を解析する最も簡単な方法は、次java.util.Scannerのように を使用することです。

import java.util.Scanner;
import java.io.File;

public class Summer {
    public static void main(String[] args)
    throws Exception
    {
        Scanner sc = new Scanner(new File("file.txt"));
        while (sc.hasNext()) {
            System.out.println(sc.nextInt());
        }
    }
}

行ごとに合計したいので、2 つのスキャナーを使用できます。

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

public class Summer {
    public static void main(String[] args)
    throws Exception
    {
        /* List to hold sums */
        ArrayList<Integer> sums = new ArrayList<Integer>();

        Scanner sc_file = new Scanner(new File("file.txt"));
        while (sc_file.hasNextLine()) {
            Scanner sc_line = new Scanner(sc_file.nextLine());

            /* Process each column within the line */
            int column = 0;
            while (sc_line.hasNext()) {
                /* When in column n, make sure list has at least n entries */
                if (column >= sums.size()) {
                    sums.add(0);
                }
                sums.set(column, sums.get(column) + sc_line.nextInt());
                column++;
            }
        }

        System.out.println(sums);
    }
}
于 2013-01-26T19:48:47.237 に答える