魔术广场印刷广场

时间:2015-02-04 15:56:33

标签: java magic-square

这是我的印刷方法

public void printSquare()
{
  DecimalFormat newSquare = new DecimalFormat("00");
  for (int row = 0; row < square.length; row++)
  {
     for (int col = 0; col < square[row].length; col++)
     {  
        System.out.print((newSquare.format(square[row][col])) + " ");
     }
  }
System.out.println();
System.out.println();

}

这是它的输出看起来像

08 01 06 03 05 07 04 09 02

这就是我需要的样子

08 01 06

03 05 07

04 09 02

我一直试图解决这个问题很长一段时间,任何帮助都将不胜感激!谢谢!

2 个答案:

答案 0 :(得分:1)

您必须在每行后添加换行符

public void printSquare()
{
  DecimalFormat newSquare = new DecimalFormat("00");
  for (int row = 0; row < square.length; row++)
  {
     for (int col = 0; col < square[row].length; col++)
     {  
        System.out.print((newSquare.format(square[row][col])) + " ");
     }
     System.out.println(); // this will print new line after each row
  }
}

答案 1 :(得分:1)

可以通过在外循环结束时使用System.out.println("\n")来修复它。

public void printSquare()
{
  DecimalFormat newSquare = new DecimalFormat("00");
  for (int row = 0; row < square.length; row++)
  {
     for (int col = 0; col < square[row].length; col++)
     {  
        System.out.print((newSquare.format(square[row][col])) + " ");
     }
     System.out.println("\n");
  }
System.out.println();
System.out.println();
}