目前正在爲C#編寫Conways人生課程。我一直在採取一些小步驟來解決語言和遊戲編程問題,並且在打印2D字符數組時遇到了麻煩。目前,我正在使用GetLength-1不能越過界限,但它無法打印出陣列中的最後一個字符。正確地打印2D陣列?
什麼我最初的文件看起來像
+*++
++*+
****
後其讀入放入CHAR(我相信)
*
*
****
什麼結束了印刷
*
**
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace ConwaysLife
{
class Program
{
static char[,] universe;
static void bigBang(int h, int w, List<string> grid)
{
universe = new char[h,w];
int row = 0;
foreach (string line in grid)
{
for (int i = 0; i < line.Length; i++)
{
if (line.ToCharArray()[i] == '*')
{
universe[row, i] = '*';
}
}
row++;
}
}
//How I'm attempting to print out my 2D char array
static void offspring()
{
StringBuilder cellLine = new StringBuilder();
for (int y = 0; y < universe.GetLength(1)-1; y++)
{
for (int x = 0; x < universe.GetLength(0)-1; x++)
{
Console.Write(universe[y, x]);
}
Console.WriteLine();
}
//pause
Console.ReadLine();
}
static void Main(string[] args)
{
List<string> tempLine = new List<string>();
//Console.WriteLine("File Path?");
int width = 0;
int height = 0;
//read file into List
using (StreamReader r = new StreamReader("life.txt"))
{
while (r.Peek() >= 0)
{
tempLine.Add(r.ReadLine());
//compare current width to new width
if (tempLine[height].Length >= width) { width = tempLine[height].Length; }
//increase height when going to next row
height++;
}
bigBang(height, width, tempLine);
}
offspring();
}
}
}
更新後代()
static void offspring()
{
StringBuilder cellLine = new StringBuilder();
for (int x = 0; x <= universe.GetLength(1); x++)
{
for (int y = 0; y <= universe.GetLength(0); y++)
{
Console.Write(universe[x, y]);
}
Console.WriteLine();
}
//pause
Console.ReadLine();
}
無關,與你真正的問題,但在C#字符串有一個索引,因此沒有必要使用「ToCharArray」,你可以做線[I] – Kippie
感謝。我可能只是把它寫下來,並認爲我找到了一條捷徑:p不要猜! – GoodBoyNYC