数组正在复制最后一行

时间:2012-11-16 00:42:07

标签: java arrays duplication

我遇到的问题是当我打印出horizontalLine(1, 1, 3, 1)时,它会将horizo​​ntalLine添加到控制台之前。有没有办法阻止重复?

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]);
                }
            }
        }
}

1 个答案:

答案 0 :(得分: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参数,因为未在实际代码中使用)