2013-06-05 29 views
1

嗨,我相當新的C#編程,請耐心等待。我目前正在研究一個「簡單」的小程序,它允許用戶在同一個文本框中輸入25個值,一旦完成,我希望能夠以列表框的形式顯示這25個值排5列,我想找出數組中最大的數字。文本框到C#窗體中的數組聲明

private void button1_Click(object sender, EventArgs e) 
{ 
    int arrayrows = 5; 
    int arraycolomns = 5; 
    int[,] arraytimes; 
    arraytimes = new int[array rows, array columns]; 

    // list_Matrix.Items.Add(tb_First.Text); 
    for (int i = 0; i != 5; i++) 
    { 
     for (int j = 0; j != 5; j++) 
     { 
      array times [i,j]= Convert. To Int32(Tb_First.Text); 
      list_Matrix.Items.Add(array times[i, j].To String()); 
     } 
    } 
} 

這是我試圖在列表框中顯示數組,但它不工作。這也阻止了我轉移到下一個發現其中最大數字的部分。

+5

相反的是完全相同的主題,每次發佈新的問題,請**提高你的第一個問題,**,並在那裏 –

+1

如果你想5行5列添加更多的細節,爲什麼'INT arrayrows = 2; int arraycolomns = 2;' – MDMalik

+0

您是否嘗試過使用string.Split方法(儘管它會給你一個一維數組)來分割你的textBox.Text,然後將這些值添加到列表框中? – NDraskovic

回答

0

您可以使用.Split('')(或任何其他字符或字符串)拆分您的字符串。這會給你一個包含25個元素的一維數組(如果一切都輸入了)。訣竅轉換其成二維陣列或網格是使用整數除法和模數,下面的代碼會以

String[] splitText = textBox.Text.Split(' '); //gets your 25-length 1D array 

//make an empty grid with the right dimensions first 
int[][] grid = new int[5][]; 
for (int i=0;i<5;i++) { 
    grid[i] = new int[5]; 
} 

//save our highest value 
int maxVal = 0; 
//then fill this grid 
for (int i=0;i<splitText.Length;i++){ 
    int value = int.Parse(splitText[i]); 
    //i%5 gives us values from 0 to 4, which is our 'x-coordinate' in the grid 
    //i/5 uses integer division so its the same as Math.floor(i/5.0), giving us your 'y-coordinates' 
    grid[i%5][i/5] = value; 

    //check if this value is larger than the one that is currently the largest 
    if (value > maxVal) 
    { 
     maxVal = value; 
    }  
} 

這將填補與分割文本框的文本的二維柵格陣列,並且如果沒有足夠的值在文本框中在這些單元格中留下0。

最後你還會得到你的最大價值。

+0

這不是工作..如果任何人有任何其他的解決方案? :( – SREEDEVI

+0

什麼是不工作? – Perry

0

請嘗試以下操作(通過以字符串形式顯示數字顯示)。假設你以下面的方式輸入數字,

「1,2,3,4 ......」

string[] nums=txtBox.Text.Split(','); 
lstBox.Items.Clear(); 
int colCount=5; 
int colIndex=0; 
string line=""; 
foreach(string num in nums) 
{ 
    if(colIndex==colCount) 
    { 
    lstBox.Items.Add(line); 
    line=""; 
    colIndex=0; 
    } 
    line+= line==""? num : " "+num; 
    colIndex+=1; 
} 
if(line!="") 
    lstBox.Items.Add(line); 

確保糾正任何語法錯誤,更改參數名稱到你。

+0

更正瞭如果在循環內的代碼中的錯誤 – WhyMe

+0

col索引的另一個錯誤:) – WhyMe

0
private void button1_Click(object sender, EventArgs e) 
     { 
      int[] ab=new int[10]; 
      string s = textBox1.Text; 
      int j = 0; 


      string [] a = (s.Split(' ')); 
      foreach (string word in a) 
      { 
       ab[j] = Convert.ToInt32(word); 
       j++; 
      } 


      for (int i = 0; i < 10; i++) 
      { 
       label2.Text +=ab[i].ToString()+" "; 
      } 
     }