2017-04-11 34 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 ");