Skip to main content
 首页 » 编程设计

c#之用文件 C# 填充锯齿状数组

2024年02月13日12oomusou

我似乎无法弄清楚如何使用 Jagged Arrays 和 Files。我有三个文件,其中包含数字,我想将每个文件读入其自己的数组。这是我到目前为止所拥有的。试图填充 [0] 数组但无济于事。任何帮助表示赞赏。也找不到任何有关执行此操作的教程。

private void button1_Click(object sender, EventArgs e) 
{ 
    StreamWriter section1; 
    StreamWriter section2; 
    StreamWriter section3; 
    StreamReader section1read; 
    StreamReader section2read; 
    StreamReader section3read; 
 
    section1 = File.CreateText("Section1.txt"); 
    section2 = File.CreateText("Section2.txt"); 
    section3 = File.CreateText("Section3.txt"); 
 
    int[][] Scores = new int[3][]; 
 
    Random randnum = new Random(); 
 
    for (int i = 0; i < 12; ++i) 
    { 
        int num = randnum.Next(55, 99); 
        section1.WriteLine(num); 
    } 
 
    for (int j = 0; j < 8; ++j) 
    { 
        int num1 = randnum.Next(55, 99); 
        section2.WriteLine(num1); 
    } 
 
    for (int k = 0; k < 10; ++k) 
    { 
        int num3 = randnum.Next(55, 99); 
        section3.WriteLine(num3); 
    } 
 
    section1.Close(); 
    section2.Close(); 
    section3.Close(); 
 
    section1read = File.OpenText("Section1.txt"); 
 
    int nums = 0; 
    while (!section1read.EndOfStream) 
    { 
        Scores[0][nums] = int.Parse(section1read.ReadLine()); 
        ++nums; 
    } 
    for (int i = 0; i < Scores.Length; ++i) 
    { 
        listBox1.Items.Add(Scores[0][i]); 
    } 
    section1read.Close(); 
} 

请您参考如下方法:

锯齿状数组应该分两步初始化:

  1. 数组本身:

    int[][] Scores = new int[3][]; 
    
  2. 子数组:

    Scores[0] = new int[12]; 
    Scores[1] = new int[8]; 
    Scores[2] = new int[10]; 
    

数组是一种固定长度的数据结构。如果事先不知道大小,则必须使用动态长度结构。最好的选择是 List<> 类:

List<List<int>> scores = new List<List<int>>(); 
 
scores.Add( new List<int>() ); 
 
using( StreamReader section1read = File.OpenText("Section1.txt")) 
{ 
    string line; 
    while ((line = section1read.ReadLine()) != null) 
    { 
        scores[0].Add(int.Parse(line)); 
    } 
} 

这里还有其他需要考虑的事情: