使用for循环在Java中创建二维坐标平面?
我正在尝试创建一个程序CoordinateFinder.java,它向用户询问两个介于1和5之间的整数值。然后,使用一对for循环生成二维坐标平面。平面应为平面上的每个坐标打印一个句点,用户指定的坐标除外,该坐标应打印一个X 我正在尝试做的示例:使用for循环在Java中创建二维坐标平面?,java,for-loop,2d,plane,Java,For Loop,2d,Plane,我正在尝试创建一个程序CoordinateFinder.java,它向用户询问两个介于1和5之间的整数值。然后,使用一对for循环生成二维坐标平面。平面应为平面上的每个坐标打印一个句点,用户指定的坐标除外,该坐标应打印一个X 我正在尝试做的示例: Enter your x coordinate: 2 Enter your y coordinate: 4 5 . . . . . 4 . X . . . 3 . . . . . 2 . . . . . 1 . . . . . 0 1
Enter your x coordinate:
2
Enter your y coordinate:
4
5 . . . . .
4 . X . . .
3 . . . . .
2 . . . . .
1 . . . . .
0 1 2 3 4 5
我所拥有的:
import java.util.Scanner;
public class CoordinateFinder {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an X co-ordinate from 1-5: ");
int x = input.nextInt();
System.out.println("Please enter a y co-ordinate from 1-5: ");
int y = input.nextInt();
for (int i = 5; i >= 1; i--) {
System.out.print(i +" ");
if (i == 0) {
System.out.println("\n");
System.out.println(" 5 4 3 2 1 ");
}
for (int j = 4; j >= 0; j--) {
System.out.print(" . ");
if (j == 0) {
System.out.println("\n");
}
}
}
}
}
哪些产出:
5 . . . . .
4 . . . . .
3 . . . . .
2 . . . . .
1 . . . . .
0
5 4 3 2 1
. . . . .
在嵌套的
FOR
循环中,变量i
表示y
值,变量j
表示x
值。因此,在每个i
循环中,您需要打印完整的行(y值),在每个“j”嵌套循环中,您确定每列中打印的内容(x值)。要确定是否需要打印X
或
,需要将i
和j
与y
和X
进行比较,如下所示:
import java.util.Scanner;
public class CoordinateFinder {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an X co-ordinate from 1-5: ");
int x = input.nextInt();
System.out.println("Please enter a y co-ordinate from 1-5: ");
int y = input.nextInt();
System.out.println("");
for (int i = 5; i >= 1; i--) {
System.out.print(i);
for (int j = 1; j <= 5; j++) {
if (i == y && j == x) {
System.out.print(" X");
} else {
System.out.print(" .");
}
}
System.out.print("\n");
}
System.out.println("0 1 2 3 4 5");
}
}
请注意,我在子循环中反转了
j
的方向,以表示在网格上从左向右遍历时增加的x值。我左I
递减,以表示向下遍历行时y值的递减。我其余的更改是格式化。是否总是6乘6的网格?是的@梅特莱普这其实很有道理。所以我们打印X行标签只是作为一个打印功能,这无关紧要吗?{System.out.println(“0 1 2 3 4 5”);}@IanHank只有网格大小不同时才重要。不能在运行时打印最后一行,但可以在原始行之外(在末尾)创建另一个FOR循环,以循环递增变量并打印数字。
Please enter an X co-ordinate from 1-5:
2
Please enter a y co-ordinate from 1-5:
4
5 . . . . .
4 . X . . .
3 . . . . .
2 . . . . .
1 . . . . .
0 1 2 3 4 5