-1
    *
  *****
*********
*********
*********
*********

这是我的代码,但它不起作用

final int WIDTH = 6;
final int HEIGHT = 9;
int i = 0;
int j = 0;

while (i < HEIGHT * 2 && j < WIDTH) {

  if ((i + (i % 2) + (WIDTH) / 2) < j // right slope
        || (i + (i % 2) + j) < (WIDTH) / 2)// left slope
  {
    System.out.print(" ");
  } 
  else {// solid then
    System.out.print("*");

  }
}

System.out.println();
i+=2;
j++;
4

2 回答 2

1

您的增量器 i 和 j 当前位于您的 while 循环右括号 (}) 之外。由于它们永远不会增加,因此 while 条件永远不会命中。导致无限循环的常见错误。

此外,如果条件的 + (i % 2) 部分毫无意义,因为您每次都将 i 增加 2,因为任何偶数 % 2 都是 0。

我的建议是手动跟踪代码,也许从较小的值开始,但这将帮助您了解出了什么问题。

于 2013-02-27T18:32:45.033 回答
0

As I mentioned in my comment, you must increment the values in your while() loop if you don't wish it to be infinite. So, perhaps add them in at the bottom!

while (i < HEIGHT) {

  if (i == 0) {
    System.out.print("    *");
  } else if (i == 1) {
    System.out.print("  *****");
  } else {// solid then
    System.out.print("**********");
  } System.out.println("");
  i++;
}

Edit: I also changed your check conditions to make them simpler. If you only have to print this one shape it should be fine, but if you will be making a variety of sizes you will need to improve your algorithm!

于 2013-02-27T18:36:28.760 回答