C#の勉強の第4回は、Consoleへの出力をアレンジ [初めてのC#]
今回は第2回で作成したプログラムと第3回で作成したプログラムを合体させて、
Console出力の整形をしてみよー
整形は、テーブルに格納したnameの値を、1行に3つづつ端を揃えて表示してみようと
思います
ex05
さて実行。
うん。できたできた
Console出力の整形をしてみよー
整形は、テーブルに格納したnameの値を、1行に3つづつ端を揃えて表示してみようと
思います
ex05
using System; //クラス配列の作成 namespace ex05 { class MyTable { public string name = ""; public int select = 0; } class ActionTable { //クラス配列の作成 public MyTable[] tb = new MyTable[0]; //クラス配列へ値をセット public int SetTableItem() { //配列のサイズ変更&インスタンス作成&データ格納 Array.Resize(ref tb, 1); tb[0] = new MyTable(); tb[0].name = "table001"; tb[0].select = 0; Array.Resize(ref tb, 2); tb[1] = new MyTable(); tb[1].name = "table0000002"; tb[1].select = 1; Array.Resize(ref tb, 3); tb[2] = new MyTable(); tb[2].name = "table3"; tb[2].select = 2; Array.Resize(ref tb, 4); tb[3] = new MyTable(); tb[3].name = "table004"; tb[3].select = 0; Array.Resize(ref tb, 5); tb[4] = new MyTable(); tb[4].name = "table000000005"; tb[4].select = 1; Array.Resize(ref tb, 6); tb[5] = new MyTable(); tb[5].name = "table6"; tb[5].select = 2; Array.Resize(ref tb, 7); tb[6] = new MyTable(); tb[6].name = "table000000007"; tb[6].select = 2; return 0; } //最長の文字列に合わせてコンソールに1行3項目で整列する。 public int ShowTableItem() { int maxLen = (TableNameMaxLen + 4) * -1 ; int cnt = 0; foreach(MyTable wtb in tb) { Console.Write(String.Format("{0," + maxLen.ToString() + "}",wtb.name)); cnt ++; if((cnt % 3)==0) {Console.WriteLine();} } Console.WriteLine(); return 0; } //テーブルに保存されている文字列の最長文字数を取得する public int TableNameMaxLen { get { int maxLen = 0; foreach(MyTable wtb in tb) { if(maxLen < wtb.name.Length ) { maxLen = wtb.name.Length;} } return maxLen; } } } class Program { public static void Main(string[] args) { ActionTable Act = new ActionTable (); //クラス配列を作成して、値をセットする int ret1 = Act.SetTableItem(); //コンソールに格納した情報を出力 int ret2 = Act.ShowTableItem(); } } }
さて実行。
うん。できたできた
コメント 0