我正在尝试创建一个程序,询问用户正方形/矩形的宽度和长度尺寸,然后使用#符号将其绘制出来。我几乎已经明白了,只是我似乎不太能正确打印出矩形的右侧...... 这是我的代码:
import java.util.Scanner;
public class warmup3
{
public static void main(String[] args)
{
int width;
int length;
Scanner sc= new Scanner(System.in);
System.out.println("How big should the width of the square be?");
width = sc.nextInt();
System.out.println("How big should the length of the square be?");
length= sc.nextInt();
{
for (int y= 0; y < length; y++)
{
for (int x= 0; x < width; x++)
{
if (x == 0 || y == 0)
{
System.out.print("#");
}
else if (x != width && y == length-1)
{
System.out.print("#");
}
else if (y != length && x == width-1)
{
System.out.print("#");
}
else
{
System.out.print("");
}
}
System.out.println("");
}
}
}
}
我知道问题出在第二个 else-if 语句上,但我无法修复它......
我无法上传此代码打印出来的图片,但基本上它是一个几乎完整的矩形,但左侧有两行#s,没有一个包围右侧(右侧是开放的)(你应该是可以自己看看)。
最佳答案
问题实际上出在最后一个 else
语句上。您需要打印一个空格 ""
,而不是打印出“nothing”或 ""
。因此将 else 语句更改为:
else
{
System.out.print(" ");
}
这样,当循环当前不在任何边缘时,它将打印出一个空格,从而在打印最后一个 # 时允许最后一个
else if
位于正确的位置
关于java - 在 Java 中根据用户输入绘制空心星号正方形/矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28529763/