2013-03-29 41 views
1

我完全新的C#和以及我想簡單代碼來創建從用戶輸入C#用戶輸入到一個2維數組

例如矩陣

int [,] matrix1 = new int [2,2] 
    // now using input i'd like to add integers into the array 
    matrix1[0,1] = Int32.Parse(Console.ReadLine()); // this is for user input 

等等。

感謝您的幫助

+3

那麼,問題出在哪裏? –

+1

@ user2223460,你需要閱讀[c#中的循環](http://csharp-station.com/Tutorial/CSharp/Lesson04)和[使用多維數組的循環](http://www.dotnetperls.com/2d -ray) – Habib

+0

如果我理解question.You需要解析用戶輸入行,並在循環中添加整數到數組。 – cosset

回答

0
Console.WriteLine("Enter the height: "); 
int h = Convert.ToInt32(Console.ReadLine()); 
Console.WriteLine("Enter the width: "); 
string w = Convert.ToInt32(Console.ReadLine()); 

int[,] arr = new int[h, w]; 

for (int i = 0; i < h; ++i) 
    for (int j = 0; j < w; ++j) 
    arr[i, j] = Convert.ToInt32(Console.ReadLine()); 
1
static void Main(string[] args) 
{ 
    int[,] matrix1 = new int[2, 2]; 

    for (int i = 0; i < 2; i++) 
    { 
     for (int j = 0; j < 2; j++) 
     { 
      matrix1[i, j] = Int32.Parse(Console.ReadLine()); 
     } 
    } 

    for (int i = 0; i < 2; i++) 
    { 
      for (int j = 0; j < 2; j++) 
      { 
      Console.WriteLine("Element({0},{1})={2}", i, j, matrix1[i, j]); 
      } 
    } 
} 
1
int[,] A = new int[5, 4]; 

//read 
for (int i = 0; i < 5; i++) 
{ 
    for (int j = 0; j < 4; j++) 
    { 
     A[i, j] = int.Parse(Console.ReadLine()); 
    } 
} 

//Write 
for (int i = 0; i < 5; i++) 
{ 
    Console.WriteLine(); 

    for (int j = 0; j < 4; j++) 
    { 
     Console.Write(A[i, j]); 
    } 
} 
0
變種

號碼=新INT [尺寸,尺寸];

  for (var i = 0; i < size; i++) 
      { 
       var numList = new string[size]; 
       numList = readLine.Split(); 
       for (var j = 0; j < size; j++) 
       { 
        numbers[i, j] =convert.ToInt32(numList[j]);       
       } 

}

1
var numbers = new int[size, size]; 

for (var i = 0; i < size; i++) 
{ 
    var numList = new string[size]; 
    numList = readLine.Split(); 
    for (var j = 0; j < size; j++) 
    { 
     numbers[i, j] = Convert.ToInt32(numList[j]);  
    } 
} 
+0

我嘗試過這種方式,並按照它應有的方式工作。請檢查並將其標記爲已回答 – mrDev

+2

SO上的代碼僅限於答案。你可以添加一些解釋,說明如何解決這個問題? –