public class tiles { public static void main (String[] args) { /* convert _87654321 into 3x3 grid * * 1 2 3 * 4 5 6 * 7 8 _ * */ // let 9 be the "empty" spot /* algorithm: - build an empty string - copy and store the original number - if we still have a number left (if copy is not zero) - divide the number by 10 - take the remainder and append to the string - subtract the remainder from the copy - divide the number by 10 and make that the number - repeat To take the reminder, - num % 10 gives the current remainder (1 digit) */ final int ORIG = 987654321; // preserve original number int copy = ORIG; // use copy to "destroy" to make the number int rem; // remainder so far (none) String s = ""; // String version of the number int size = (int) Math.sqrt((""+ORIG).length()); // size of square grid int count = 0; // current # of elements processed in row // build grid: while (copy!=0) { // retrieve current digit: rem = copy % 10; copy -= rem; copy = copy/10; // note: integer division! // adjust for blank if (rem==9) s += " "; else s += rem; // adjust for new line (end of row) count++; if (count==size) { s +="\n"; count = 0; } } System.out.println(s); // Note: Using a for-loop would certainly help. // Why didn't I? I avoid the problem of an out-of-bounds int. // Realistically, you would use a for-loop though :-) } }