我正在尝试用java编写一段代码来打印图形中的正方形以及图形的轴。它询问用户正方形在图表中的位置以及边长。我已经编写了这段代码,它确实打印了轴,但不打印正方形。请帮我找出问题所在:
public static void main(String[] args) {
int xStart = 0, xEnd = 14, yStart = 14, yEnd = 0;
Scanner scnr = new Scanner(System.in);
System.out.print("Position in x:");
int positionInX = Integer.parseInt(scnr.nextLine());
System.out.print("Position in y:");
int positionInY = Integer.parseInt(scnr.nextLine());
System.out.print("Length of the square:");
int lengthOfSquare = Integer.parseInt(scnr.nextLine());
System.out.println("^");
for (int y = yEnd; y <= yStart; y++){
System.out.println("|");
if (y == yStart){
System.out.print("+");
}
for (int x = xStart; x <= xEnd && y == yStart; x++){
System.out.print("-");
if (y <= (lengthOfSquare + positionInY) && y >= (positionInY) && x <= (lengthOfSquare + positionInX) && x >= (positionInX)) {
System.out.print("#");
}
else if (x != xStart && y != yStart) {
System.out.print(" ");
}
if(x == xEnd){
System.out.println(">");
}
}
}
}
}
它应该看起来像这样(假设 x = 0 中的位置,y = 0 中的位置,并且长度 = 4):
^
|
|
|
|
|
|
|
|
|
|
|
|####
|####
|####
|####
+--------------->
最佳答案
这里有一个主要问题:
int xStart = 0, xEnd = 15, yStart = 0, yEnd = 15;
for (int y = yEnd; y <= yStart; y++) {
循环从 y
等于 15 (yEnd
) 开始,一直持续到 y
小于或等于0
(yStart
)。
它永远不会执行。
我不明白为什么您要以 yEnd
开始循环并以 yStart
结束。为什么 yEnd
会静态分配给 15。yEnd
是否应该分配给用户输入的 y 值?
关于java - 在java中打印图形中的正方形+轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21654327/