簡體   English   中英

讀取文件並將值存儲到2D數組中

[英]read file and store values into a 2D array

我有一個包含以下內容的文件:

S5555; 100 70 70 100
S3333; 50 50 50 50
S2222; 20 50 40 70
S1111; 90 80 90 85
S4444; 70 80 90 50

用戶單擊按鈕1時,應將存儲學生ID的文件加載到studentIDArr中(例如S5555),將其他值加載到4x5數組marksMatrix中,每個值在數組中占據一個位置。

我是否將值正確存儲到studentIDArr中? 至於marksMatrix,我試圖粗略地寫出我認為它是如何工作的,但是我也不是很確定(有人評論了)。 我只能為此使用數組。

string[,] marksMatrix = new string[4,5];
string[] studentIDArr = new string[5];

private void button1_Click(object sender, EventArgs e)
{
    textBox2.Clear();

    try
    {
        using (StreamReader sr = new StreamReader("C:/Users/Y400/dDesktop/CTPrac/CTPrac/input.txt"))
        {
            string x = null;
            while ((x = sr.ReadLine()) != null)
            {
                for (int j = 0; j < studentIDArr.Length; j++)
                {
                    studentIDArr[j] = x;
                }
            }
        }

        textBox2.Text = "File Loading done.\r\n";
        textBox2.Text += "Number of records read: " + studentIDArr.Length;
    }
    catch (IOException ex)
    {
        textBox2.Text = "The file could not be read. " + ex.Message;
    }

    string a, b, c;
    for (int i = 0; i < studentIDArr.Length; i++)
    {
        //a = (String)studentIDArr[i];

        //    string[] abc = Regex.Split(a, ";");
        //    b = abc[0];
        //    c = abc[1];
        //    bc =; 

        for (int y = 0; y < 6; y++)
        {
            for (int x = 0; x < 5; x++)
            {
                //marksMatrix[y, x] = z;
            }
        }
    }

    button1.Enabled = false;
}

您可以使用for循環簡單地做到這一點。

string[,] marksMatrix = new string[4, 5];
string[] studentIDArr = new string[5];

var lines = File.ReadAllLines("C:/Users/Y400/dDesktop/CTPrac/CTPrac/input.txt");
for (int i = 0; i < lines.Length; i++)
{
    var parts = lines[i].Split(new[] {';', ' ' });
    studentIDArr[i] = parts[0];
    for (int j = 1; j < parts.Length; j++)
    {
        marksMatrix[j - 1, i] = parts[j];
    }
}

這種編碼方式難以理解,請嘗試定義一個類來存儲學生ID和標記。

 public class Student
 {
     public string Id { get; set; }
     public List<string> Marks { get; set; }

     public Student()
     {
         this.Marks = new List<string>();
     }
 }

然后代碼將如下所示

var students = new List<Student>();
foreach (var line in File.ReadLines("C:/Users/Y400/dDesktop/CTPrac/CTPrac/input.txt"))
{
    var parts = line.Split(new[]{';', ' '}).ToList();
    students.Add(new Student()
    {
        Id = parts[0],
        Marks = parts.GetRange(1, 4)
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM