0

我遇到的问题是当我打印出来时,horizontalLine(1, 1, 3, 1)它会在它之前添加水平线到控制台中。有什么办法可以阻止复制吗?

public class Array {

static String arrayPicture[][];

public static void main (String[] args) {

    arrayPicture = new String [5][5];

    for (int i = 0; i < 5; i ++) {

        for (int j = 0; j < 5; j ++) {
            arrayPicture [i][j] = " ";
    }
}
        horizontalLine (0, 0, 4, 0);
        horizontalLine (1, 1, 3, 1);
}
public static void horizontalLine (int x1, int y1, int x2, int y2) {

            for (int k = x1; k < x2; k ++) {
                arrayPicture [y1][k] = "*";
            }
            picture();
            System.out.println ();
}
public static void picture () {
            for (int i = 0; i < 5; i ++) {

            for (int j = 0; j < 5; j ++) {
                System.out.print (arrayPicture[i][j]);
                }
            }
        }
}
4

1 回答 1

0

一切都发生在该picture()方法中,因为为了打印第二个数组,您的索引重新开始0...

这里有一个解决方案,注意picture()方法的参数:(即使代码最初可读性不好)

class Array {

    static String arrayPicture[][];

    public static void main(String[] args) {

        arrayPicture = new String[5][5];

        for (int i = 0; i < 5; i++) {

            for (int j = 0; j < 5; j++) {
                arrayPicture[i][j] = " ";
            }
        }
        horizontalLine(0, 0, 4);
        horizontalLine(1, 1, 3);
    }

    public static void horizontalLine(int x1, int y1, int x2) {

        for (int k = x1; k < x2; k++) {
            arrayPicture[y1][k] = "*";
        }
        picture(y1);
        System.out.println();
    }

    public static void picture(int startIndex) {
        for (int i = startIndex; i < 5; i++) { // start from startIndex, not necessary 0 !
            for (int j = 0; j < 5; j++) {
                System.out.print(arrayPicture[i][j]);
            }
        }
    }
}

输出:

****                     
 ** 

(我删除了y2参数,因为没有在您的实际代码中使用)

于 2012-11-16T00:51:39.370 回答