打印阵列产生八字形图案

时间:2014-03-03 12:40:26

标签: java arrays console

我有一个数组的结果,我想在图8和下面打印它们是执行此操作的代码:

tempString2 = "\t" + trainTrack[5]+ "\n" + trainTrack[4] + "\t\t"
+ trainTrack[6] + "\n"+ trainTrack[3] + "\t\t" + trainTrack[7]+ "\n"
+ trainTrack[2] + "\t\t" + trainTrack[8]  + "\n"+ trainTrack[1]  + "\t\t"
+ trainTrack[9]  + "\n\t" + trainTrack[0]  + "\n"+ trainTrack[10] + "\t\t"
+ trainTrack[18] + "\n" + trainTrack[11] + "\t\t" + trainTrack[17] + "\n"
+ trainTrack[12] + "\t\t" + trainTrack[16] + "\n"+ trainTrack[13] + "\t\t"
+ trainTrack[15] + "\n\t" + trainTrack[14];

及以下是输出字符串时显示的内容:

      [..]
[..]        [..]
[..]        [..]
[..]        [..]
[..]        [..]
      [..]
[..]        [..]
[..]        [..]
[..]        [..]
[..]        [..]
      [..]

但是有没有一种方法可以让它变得更加漂亮,边缘更圆,所以实际看起来像八个?

2 个答案:

答案 0 :(得分:0)

这个怎么样?

  [..][..]
[..]    [..]
[..]    [..]
[..]    [..]
[..][..][..]
[..]    [..]
[..]    [..]
[..]    [..]
  [..][..]

看起来更干净,更合适。 (也是圆的)

答案 1 :(得分:0)

我不确定这是否是你想要的答案,但你可以试试这个:

tempString2 = "      " + trainTrack[5]+ "\n  " + trainTrack[4] + "    " + trainTrack[6]
    + "\n"+ trainTrack[3] + "        " + trainTrack[7]  + "\n"+ trainTrack[2] + "        "
    + trainTrack[8] + "\n  "+ trainTrack[1] + "    " + trainTrack[9] + "\n      "
    + trainTrack[0] + "\n  "+ trainTrack[10] + "    " + trainTrack[18] + "\n"+ trainTrack[11]
    + "        " + trainTrack[17]   + "\n"+ trainTrack[12] + "        " + trainTrack[16]
    + "\n  "+ trainTrack[13] + "    " + trainTrack[15] + "\n      " + trainTrack[14];

输出:

      [..]
  [..]    [..]
[..]        [..]
[..]        [..]
  [..]    [..]
      [..]
  [..]    [..]
[..]        [..]
[..]        [..]
  [..]    [..]
      [..]

您也可以使用String.format()获得相同的结果。它使一个更小,更整洁,但不太容易理解的程序:

String tempString2 = String.format("%10s\n%6s%8s\n%4s%12s\n%4s%12s\n%6s%8s\n%10s\n%6s%8s\n%4s%12s\n%4s%12s\n%6s%8s\n%10s",
    trainTrack[5], trainTrack[4], trainTrack[6], trainTrack[3], trainTrack[7], trainTrack[2],
    trainTrack[8], trainTrack[1], trainTrack[9], trainTrack[0], trainTrack[10],
    trainTrack[18], trainTrack[11], trainTrack[17], trainTrack[12], trainTrack[16],
    trainTrack[13], trainTrack[15], trainTrack[14]);