2017-04-11 32 views
1

我試圖讓我的「遊戲」出現在這段代碼的每一行但它一直出現在年底前,我無法工作,如何解決我的環使它會在正確的時間創建一個新行。For循環使用有序陣列格式錯誤

static void Main() { 

      int[,] lottoNumbers ={ 
            { 4, 7, 19, 23, 28, 36}, 
            {14, 18, 26, 34, 38, 45}, 
            { 8, 10,11, 19, 28, 30}, 
            {15, 17, 19, 24, 43, 44}, 
            {10, 27, 29, 30, 32, 41}, 
            { 9, 13, 26, 32, 37, 43}, 
            { 1, 3, 25, 27, 35, 41}, 
            { 7, 9, 17, 26, 28, 44}, 
            {17, 18, 20, 28, 33, 38} 
           }; 

      int[] drawNumbers = new int[] { 44, 9, 17, 43, 26, 7, 28, 19 }; 

      PrintLottoNumbers(lottoNumbers); 

      ExitProgram(); 
     }//end Main 

static void PrintLottoNumbers(int[,] lottoN) 
     { 
      for (int x = 0; x < lottoN.GetLength(0); x++) { 
       for (int y = 0; y < lottoN.GetLength(1); y++) { 
        if(y < 1 && x > 0) 
        { 
         Console.WriteLine("Game" + lottoN[x, y] + " "); 
        }else { 
         Console.Write($"{lottoN[x, y],2}" + " "); 
         //Console.Write(lottoN[x, y] + " "); 
        } 

       } 
      } 

     }//Print Function For Lotto Numbers 

回答

1

試試這個格式:

 for (int x = 0; x < lottoNumbers.GetLength(0); x++) 
     { 
      Console.Write("Game" + lottoNumbers[x, 0] + "\t"); 
      for (int y = 0; y < lottoNumbers.GetLength(1); y++) 
      { 
       Console.Write($"{lottoNumbers[x, y],2}" + "\t"); 
      } 
      Console.WriteLine(); 
     } 
+0

完美!非常感謝你們! – BobFisher3

1

看看你的代碼

Console.WriteLine("Game" + lottoN[x, y] + " "); 
}else { 
Console.Write($"{lottoN[x, y],2}" + " "); 

這裏你說的寫出來的文字遊戲+的東西,並用線終止,否則,只寫額外的東西到現有的行。

例如,也許它顯示

Game 1 2 3 4 5 game 1 
2 3 4 5 

如果你需要遊戲是在一行的開頭,先發送一個換行!林大概猜測

Console.Writeline();  
Console.Write("Game" + lottoN[x, y] + " "); 
}else { 
Console.Write($"{lottoN[x, y],2}" + " "); 

可能是更你想要

game 1 2 3 4 5 
game 1 2 3 4 5 
+0

四處逛逛!現在在第一個號碼後面有一個空格:3 – BobFisher3

0

最清潔和最易讀的方式我s將一行條目的文本創建爲單獨的方法,然後爲每一行調用該條目。事情是這樣的:

static void PrintLottoNumbers(int[,] lottoN) 
    { 
     for (int x = 0; x < lottoN.GetLength(0); x++) 
     { 
      Console.WriteLine("Game" + GetRowText(lottoN, x)); 
     } 

    }//Print Function For Lotto Numbers 

    static string GetRowText(int[,] lottoN, int row) 
    { 
     var builder = new StringBuilder(); 
     for (int x = 0; x < lottoN.GetLength(1); x++) 
     { 
      builder.Append(" " + lottoN[row, x]); 
     } 
     return builder.ToString(); 
    } 
1

爲什麼有if-else

 for (int x = 0; x < lottoN.GetLength(0); x++) { 
      Console.Write("\nGame "); 
      for (int y = 0; y < lottoN.GetLength(1); y++) { 
       Console.Write($"{lottoN[x, y],2}"); 
      } 
     } 

就移動遊戲的寫作在第一循環的事情複雜化。

這會打印一個額外的空白行,但爲了避免您可以添加額外的條件。

Console.Write((x!=0 ? "\n" : string.Empty) + "Game ");