loukios loukios - 7 months ago 11
Java Question

Printing square pattern in Java -- off by one error

I would to print the following pattern but I don't get the first column and the first row, which I don't really understand. Maybe an off by one error, but how to correct it ? Thanks for explanation.

The expected output :

00 10 20 30 40 50 60 70 80 90
01 11 21 31 41 51 61 71 81 91
02 12 22 32 42 52 62 72 82 92
03 13 23 33 43 53 63 73 83 93
04 14 24 34 44 54 64 74 84 94
05 15 25 35 45 55 65 75 85 95
06 16 26 36 46 56 66 76 86 96
07 17 27 37 47 57 67 77 87 97
08 18 28 38 48 58 68 78 88 98
09 19 29 39 49 59 69 79 89 99


The code :

public static void main (String args[]) {

for(int row=0;row<9;row++){
int x;
x=row;
x++;

for(int col=0;col<9;col++){
x = x+10;
StringBuilder mySB = new StringBuilder(x+" ");
System.out.print(mySB);
}

System.out.println();

}
}

Answer

You need to put x = x + 10 after you print, and remove the x++; line.

You also need to go to <=9 or <10 because you're missing the 9s:

public static void main (String args[]) {  

    for(int row=0;row<10;row++){
        int x;
        x=row;

        for(int col=0;col<10;col++){ 
           StringBuilder mySB = new StringBuilder(x+" ");
           System.out.print(mySB);   
           x = x+10;  
        }

        System.out.println();

    }
}

Edit Nifty Java 8 way of doing it:

private static class Grid {

    public static void outputGrid() {
        IntStream
            .range(0, 10)
            .mapToObj(Grid::generateRow)
            .forEach(System.out::println);
    }

    private static String generateRow(int row) {
        return IntStream
            .range(0, 10)
            .mapToObj(col -> String.format("%d%d", col, row))
            .collect(Collectors.joining(" "));
    }
}

public static void main(String []args){
   Grid.outputGrid();
}