【问题标题】:How to form a diamond in Java [duplicate]如何在Java中形成钻石[重复]
【发布时间】:2015-02-10 22:10:20
【问题描述】:

我想弄清楚为什么我的钻石没有完全在底部形成。当用户输入任何大于 3 的奇数时,菱形不会在底部正确形成(它只在最大的中间行之后打印一行)。它看起来像这样(我在这个例子中尝试了五行):

    * 
   * * 
  * * * 
   * *

我认为应该创建菱形底部的 for 循环有问题。代码是:

//bottom of the diamond
for (j = (in + 1) / 2; j < in; j++) {
    // similar to the first for statement instead
    // when j equals the user's input plus one
    // divided by two it will then go to the next
    // for loop (the diamond starts to shrink)
    for (i = 1; i < j; i++) {
        //when i equals one, and j is greater than one
        System.out.print(" "); //prints space
    }
    //similar to the for loop that prints the asterisk
    // to the left this for loop goes through when
    // l equals zero, and this time is less than
    // the user's input minus j
    for (l = 0; l < in - j; j++) {
        System.out.print(" *"); //prints the bottom asterisks
    }
    System.out.println(""); //starts another blank new line
}
// just like the top section it keeps looping
// until the requirements are no longer met

我做错了什么?

【问题讨论】:

  • l = 0; l &lt; in - j; j++ 我想你想用l++
  • 感谢您的更正(很惊讶我错过了那个错字)!

标签: java for-loop nested integer println


【解决方案1】:

虽然 Lashane 在他的评论中指出了当前的问题,但我注意到你的逻辑比它需要的要复杂。

所以,回答你的问题

我做错了什么?

请允许我提供一个不太容易混淆的实现,它对菱形的顶部和底部使用相同的循环体代码。

int in = 5;
for (int j = 1; j <= in; j++) {
  for (int i = 0; i < in - j; i++) {
    System.out.print(" ");
  }
  for (int i = 0; i < j; i++) {
    System.out.print(" *");
  }
  System.out.println("");
}
for (int j = in - 1; j >= 1; j--) {
  for (int i = 0; i < in - j; i++) {
    System.out.print(" ");
  }
  for (int i = 0; i < j; i++) {
    System.out.print(" *");
  }
  System.out.println("");
}

现在两个 for 循环之间的唯一区别是第一个从 1 向上计数到 in,第二个从 in - 1 向下计数到 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 2017-05-17
    • 2017-01-04
    • 2014-09-18
    相关资源
    最近更新 更多