【发布时间】:2014-06-01 05:21:35
【问题描述】:
我已经搜索过这个问题的简单解决方案。
我有一个方法叫
printCross(int size,char display)
它接受一个大小并打印一个 X,它接收到的 char 变量是大小的高度和宽度。
调用方法printShape(int maxSize, char display) 接受形状的最大尺寸并进入一个循环,将 2 的倍数发送到 printCross 方法,直到达到最大值。
这是我的代码,但它没有给我想要的结果。
public static void drawShape(char display, int maxSize)
{
int currentSize = 2; //start at 2 and increase in multiples of 2 till maxSize
while(currentSize<=maxSize)
{
printCross(currentSize,display);
currentSize = currentSize + 2;//increment by multiples of 2
}
}
public static void printCross(int size, char display)
{
for (int row = 0; row<size; row++)
{
for (int col=0; col<size; col++)
{
if (row == col)
System.out.print(display);
if (row == 1 && col == 5)
System.out.print(display);
if (row == 2 && col == 4)
System.out.print(display);
if ( row == 4 && col == 2)
System.out.print(display);
if (row == 5 && col == 1)
System.out.print(display);
else
System.out.print(" ");
}
System.out.println();
}
}
是因为我将数字硬编码到循环中吗?我做了很多数学运算,但不幸的是,只有这样我才稍微接近了我想要的输出。
If the printCross() method received a size of 5 for instance, the output should be like this:
x x
x x
x
x x
x x
拜托,我已经为此花费了数周时间,但似乎无处可去。谢谢
【问题讨论】:
-
您是否尝试过手动运行程序(使用笔和纸)看看它是如何出错的?
-
好建议。另一种是使用调试器。
-
- 如果以下答案之一特别有用,请选择该答案旁边的复选符号,或单击向上箭头,或同时单击两者:)
标签: java methods char nested-loops shapes