0

こんにちは、

私は現在、次の形式のファイルの読み取りに取り組んでいます

5 5
0     0     0     0     0
0     0     0     0     0
0     0     0     0     0
0     0     0     0     0
0     0     0     0     0

2D配列に。

最初の行は、2D配列(つまり、5x5)の行の長さと列の長さです。

後続の行には、array [0] [0] = 0、array [0] [1] = 0などの2D配列に読み込む必要のある入力値(値自体は整数であるだけでなく重要です)が与えられます。 。

私が現在嫌いなのは、最初の行の後にファイルの内容を読み取り、それを表示することです。これまでのところ、

public static void importFile(String fileName) throws IOException 
{
    int rows = 0;
    int cols = 0;

    int[][] numArray = null;

    try {
        int count = 0;

        BufferedReader reader = new BufferedReader(new FileReader(fileName));

        String line;
        while ((line = reader.readLine()) != null) 
        {
           count++;

            if (count == 1) 
            {
                String[] tokenizer = line.split("\\s+");

                rows = Integer.parseInt(tokenizer[0]);
                System.out.println(rows);

                cols = Integer.parseInt(tokenizer[1]);
                System.out.println(cols);

                numArray = new int[rows][cols];

            } // end of if statement
            else if(count > 1)
            {
                String[] tokenizer = line.split("   ");

                    for(int j = 0; j < tokenizer.length; j++)
                    {
                        numArray[rows][j] = Integer.parseInt(tokenizer[j]);
                        System.out.print(numArray[rows][j] + " ");
                    }
                    System.out.println("");

                rows++;

            } // end of else if

        }// end of while loop

    } //end of try statement
    catch (Exception ex) {
        System.out.println("The code throws an exception");
        System.out.println(ex.getMessage());
    } 

    System.out.println("I am printing the matrix: ");
    for (int i = 0; i < rows; i++) {
        for(int j=0; j < cols; j++)
            System.out.print(numArray[i][j] + " ");
        System.out.println("");
    }  
} // end of import file

}//クラスの終わり出力は指定されたとおりです

Please enter the file you'd like to use: 
data4.txt
5
5
The code throws an exception
5
I am printing the matrix: 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
4

3 に答える 3

1

あなたは物事を複雑にしすぎていると思います。ファイル形式が常に正しいと想定できる場合は、安全に使用できます

String[] tokenizer = line.split(" "); // you have this line of code already.
rows = Integer.parseInt(tokenizer[0]);
cols = Integer.parseInt(tokenizer[1]);

これにより、最初の行を読み取る際の問題が解決されます。

問題は次のコード行です。

rows = tempLine;

値をtempLineint tempLine = line.charAt(i);)に設定すると、の値が得intられますchar。のint値はchar '5'5ではなく53です。これは、文字のASCIIコードだからです'5'

于 2013-01-23T19:32:21.240 に答える
0

私は他の答えの下で拡張された議論をしました。あなたのコードはあなたが試した(そしてかなり近い)ことを示しているので、私はあなたの問題に対する強力な解決策を投稿します。あなたのプログラムにはたくさんの小さなバグがあり、それぞれについて詳しく説明するのはもっと手間がかかるので、私はそれを完全に書き直しました。次のメソッドは、指定された形式のファイルを読み取り、結果のを返しますint[][]。ファイルにエラーがある場合、メソッドはあなたに教えてくれます;)

public static int[][] importFile(String fileName) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    int[][] numArray;
    String line = reader.readLine();
    if (line == null) {
        throw new IllegalArgumentException("There was no 1st line.");
    }
    String[] dimensions = line.split("\\s+");
    try {
        int rows = Integer.parseInt(dimensions[0]);
        int cols = Integer.parseInt(dimensions[1]);
        // TODO: check for negative values.
        numArray = new int[rows][cols];
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("First line of file has to be 'rows cols'");
    }

    int row = 0; 

    while ((line = reader.readLine()) != null && row < numArray.length) {
        String[] tokens = line.split("\\s+");
        if (tokens.length > numArray[row].length) {
            throw new IllegalArgumentException("Too many values provided in matrix row " + row);
        }
        // to less values will be filled with 0. If you don't want that
        // you have to uncomment the next 3 lines.
        //if (tokens.length < numArray[row].length) {
        //  throw new IllegalArgumentException("Not enough values provided in matrix row " + row);
        //}
        for(int column = 0; column < tokens.length; column++) {
            try {
                int value = Integer.parseInt(tokens[column]);
                numArray[row][column] = value; 
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("Non numeric value found in matrix row " + row + ", column " + column);
            }
        }
        row++;
    }
    if (line != null) {
        // there were too many rows provided.
        // Superflous ones are ignored.
        // You can also throw exception, if you want.
    }
    if (row < numArray.length) {
        // There were too less rows in the file. If that's OK, the
        // missing rows will be interpreted as all 0.
        // If that's OK with you, you can comment out this whole
        // if block
        throw new IllegalArgumentException("Expected " + numArray.length + " rows, there only were " + row);
    }
    try {
        reader.close(); // never forget to close a stream.
    } catch (IOException e) { }
    return numArray;
}
于 2013-01-23T22:41:35.027 に答える
0

最初の行の場合:

if (count == 1) {
                String[] tokenizer = line.split(" ");
                row=Integer.parseInt(tokenizer[0]);
                col=Integer.parseInt(tokenizer[1]);
                System.out.println("There are " + cols + " colums");
                numArray = new int[row][col];
            } // end of if statement 

配列を埋めるため

            String[] tokenizer = line.split(" ");
            for(int j=0;j<col;j++){
            numArray[0][j]=Integer.parseInt(tokenizer[j]);      //fill the array from tokenizer
            }
于 2013-01-23T19:44:03.880 に答える