-1

これは、ファイルからデータを取得して配列に配置するファイリング関数です。

public void populate_grid_by_file()
    {
        String store_data_from_file = string.Empty;
        try
        {
            using (StreamReader reader = new StreamReader("data.txt"))
            {
                store_data_from_file = reader.ReadToEnd().ToString();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        string[] line = store_data_from_file.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
        for (int i = 0; i < line.Length; i++)
        {
            string[] alphabet = store_data_from_file.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
            for (int j = 0; j < alphabet.Length; j++)
            {
                Sodoku_Gri[i, j] = alphabet[j];
            }
        }            
    }

ファイルに書かれている内容は次のとおりです。

1--2--3--

3-4-4-5--

-7-3-4---

7--5--3-6

--7---4--

3-2--4-5-

------3--

2-6--7---

4---4--3-

これは私が印刷したいものです:

1 - - 2 - - 3 - -
3 - 4 - 4 - 5 - -
- 7 - 3 - 4 - - -
7 - - 5 - - 3 - 6
- - 7 - - - 4 - -
3 - 2 - - 4 - 5 -
- - - - - - 3 - -
2 - 6 - - 7 - - -
4 - - - 4 - - 3 -

私はこのようにすることを考えました:

public void display_grid()
    {
        for (int row = 0; row < Sodoku_Gri.GetLength(0); row++)
        {
            for (int col = 0; col < Sodoku_Gri.GetLength(1); col++)
            {

                Console.Write(Sodoku_Gri[row, col]);
                Console.Write("  ");
            }
            Console.WriteLine();
        }
    }

最後の行に ------------ を追加して 2 次元配列が 9 回印刷された理由がわかりません。

ファイル内のデータを示したように、各要素間に間隔がある2次元配列である必要がありますが、間隔はありません。

4

1 に答える 1

1

データを行に分割しています。内側のループでの意図は、現在の行の文字を処理することです。ただし、実際には各行の反復でファイル全体を処理しているため、出力にはファイルのすべての文字 * 行数が含まれます。代わりに次の調整を試してください。

   public void populate_grid_by_file()
        {
            String store_data_from_file = string.Empty;
            try
            {
                using (StreamReader reader = new StreamReader("data.txt"))
                {
                    store_data_from_file = reader.ReadToEnd().ToString();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            string[] line = store_data_from_file.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < line.Length; i++)
            {
                //string[] alphabet = store_data_from_file.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
                string[] alphabet = line[i].Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)
                for (int j = 0; j < alphabet.Length; j++)
                {
                    Sodoku_Gri[i, j] = alphabet[j];
                }
            }            
        }
于 2012-12-07T19:14:10.597 に答える