首页 > 解决方案 > 打印 x & y 坐标图并显示绘图点的 Java 程序

问题描述

我必须打印一个 6 x 6 的图表并绘制一个给定的点。这是 x=2 和 y=3 的示例:

 5 . . . . . 
 4 . . . . . 
 3 . x . . . 
 2 . . . . . 
 1 . . . . . 
 0 1 2 3 4 5 

我的代码:

public static String[][] plotPoint(String[][] plot){
    int x=0, y=0;
    Scanner sc = new Scanner(System.in);
    boolean bool = true;
    while(bool) {
        System.out.println("Enter x coordinate between 0 and 5: ");
        x = sc.nextInt();
        System.out.println("Enter y coordinate between 0 and 5: ");
        y = sc.nextInt();

        if(x>=5||x<0||y>=5||y<0) {
            System.out.println("The coordinates entered exceed the limit.");
        }else {
            x = x-1;
            bool=false;
        }
    }
    for(int i=0; i<6; i++) {
        for(int j = 0; j<6; j++) {
            if(i==x && j==y) {

                plot[x][y]="x";//assigning "x" to coordinates
                break;
            }
        }
    }
    return plot;

}

 public static void main(String [] args) {
    int h = 5;
    Scanner sc = new Scanner(System.in);
    String [][] strArr = new String[6][6];
    char c='.';
    for(int i = 0; i<6; i++) {
        for(int j = 0; j<6; j++) {
            if(j==0||i==5) {
                strArr[i][j] = Integer.toString(h);
                if(i==5)h++;
                else h--;
            }
            else {
                strArr[i][j]= Character.toString(c);
            }
        }
    }

    String[][] nStrArr = new String[6][6];
    nStrArr = plotPoint(strArr);
    for(int i = 0; i<6; i++) {
        for(int j = 0; j<6; j++) {
            System.out.print(nStrArr[i][j]+ " ");
        }
        System.out.println();
    }
}

目前它正在正确打印图表,但该点完全错误,我认为我的 plotPoint 方法中的第二个 if 语句不正确,但我不确定还能尝试什么。

标签: javamultidimensional-array

解决方案


我认为for不需要在图中标记循环x。尝试这个。

public static String[][] plotPoint(String[][] plot) {
    int x = 0, y = 0;
    Scanner sc = new Scanner(System.in);
    boolean bool = true;
    while (bool) {
        System.out.println("Enter x coordinate between 0 and 5: ");
        x = sc.nextInt();
        System.out.println("Enter y coordinate between 0 and 5: ");
        y = sc.nextInt();

        if (x >= 5 || x < 0 || y >= 5 || y < 0) {
            System.out.println("The coordinates entered exceed the limit.");
        } else {
            y = y + 1;
            bool = false;
        }
    }
    plot[plot.length - y][x] = "x";
    return plot;
}

推荐阅读