Search code examples
javaarraysduplication

Array is duplicating the last line


The problem I am having is when I print out horizontalLine(1, 1, 3, 1) it adds the horizontalLine before it into the console. Is there any way to stop the duplication?

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

Solution

  • All happens in the picture() method because in order to print the second array, your index restarts to 0 ...

    Here a solution, note the argument for the picture() method: (even if the code is originally not well readable)

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

    Output:

    ****                     
     ** 
    

    (I removed y2 argument since not used within your actual code)