我正在尝试创建一个依赖于用户输入的2到10之间的整数的程序。
如果用户输入四个,则应为输出:
****
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
****
我希望输入4以在第一行输出四颗星以形成水平边缘,然后在输出中形成四颗对角线。然后沿着垂直的“边缘”四颗星,然后重复对角线和水平边缘。
因此我可以正确地绘制第一行,最后一行和中间行,但是由于某种原因,我的对角线甚至不会显示空格!
****
**
**
**
**
* *
* *
* *
* *
**
**
**
**
****
这是我的代码(我是一个初学者,但是我一直在试图解决这个问题,我确实需要一些帮助):
int num = 0;
System.out.println("Enter a value between 2 and 10.");
num = keyNum.nextInt();
while (num < 2 || num > 10) {
System.out.println("Enter a valid number please.");
num = keyNum.nextInt();
}
for (int a = 0; a < num + 1; a++)
{
System.out.print(" ");
}
for (int b = 0; b < num; b++)
{
System.out.print("*");
}
for (int c = 0; c < num; c++)
{
System.out.println("");
for (int d = num; d < 1; d--)
{
System.out.print(" ");
}
System.out.print("*");
for (int e = (num * 3) - 2; e < num; e++)
{
System.out.print(" ");
}
System.out.print("*");
}
for (int f = 0; f < num; f++)
{
System.out.println("");
System.out.print("*");
for (int g = 0; g < num * 3; g++)
{
System.out.print(" ");
}
System.out.print("*");
}
for (int h = 0; h < num; h++)
{
System.out.println("");
for (int i = num; i < 1; i--)
{
System.out.print(" ");
}
System.out.print("*");
for (int j = (num * 3) - 2; j < num; j++)
{
System.out.print(" ");
}
System.out.print("*");
}
System.out.println("");
for (int k = 0; k < num + 1; k++)
{
System.out.print(" ");
}
for (int l = 0; l < num; l++)
{
System.out.print("*");
}
任何帮助将不胜感激!谢谢。
答案 0 :(得分:1)
这应该有效
刚刚更改了几个for
循环条件
while (num < 2 || num > 10) {
System.out.println("Enter a valid number please.");
num = keyNum.nextInt();
}
for (int a = 0; a < num + 1; a++)
{
System.out.print(" ");
}
for (int b = 0; b < num; b++)
{
System.out.print("*");
}
for (int c = 0; c < num; c++)
{
System.out.println("");
for (int d = num; d > c; d--)
{
System.out.print(" ");
}
System.out.print("*");
for (int e = num * 2; e < (num * 3) + (c *2); e++)
{
System.out.print(" ");
}
System.out.print("*");
}
for (int f = 0; f < num; f++)
{
System.out.println("");
System.out.print("*");
for (int g = 0; g < num * 3; g++)
{
System.out.print(" ");
}
System.out.print("*");
}
for (int h = 1; h <= num; h++)
{
System.out.println("");
for (int i = 0; i < h; i++)
{
System.out.print(" ");
}
System.out.print("*");
for (int j = 0; j < (num * 3) - (h * 2) ; j++)
{
System.out.print(" ");
}
System.out.print("*");
}
System.out.println("");
for (int k = 0; k < num + 1; k++)
{
System.out.print(" ");
}
for (int l = 0; l < num; l++)
{
System.out.print("*");
}