Advertisement
richarduie

PrintGrid.java

Oct 30th, 2013
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. import java.util.InputMismatchException;
  2. import java.util.Scanner;
  3.  
  4.  
  5. public class PrintGrid
  6. {
  7.     public static void main( String[] args ) {
  8.         Scanner scan = new Scanner( System.in );
  9.         int rows = readInt(
  10.             "How many rows (positive integer)?", scan
  11.         );
  12.         int cols = readInt(
  13.             "How many columns (positive integer)?", scan
  14.         );
  15.        
  16.         print( rows, cols );
  17.     }
  18.    
  19.     private static void print( int rows, int cols ) {
  20.         // display width to which each number should be padded
  21.         int maxWidth = 2 + ("" + rows*cols).length();
  22.         // THIS IS THE PART YOU WANT...REST IS PROOF-OF-CONCEPT
  23.         for (int i = 1; i <= rows; i++) {
  24.             for (int j = 0; j < cols; j++) {
  25.                 // i + j*rows with i running from 1 to rows and
  26.                 // j running from 0 to cols - 1 is the answer
  27.                 System.out.print( pad( maxWidth, i + j*rows ));
  28.             }
  29.             System.out.println();   // start next row
  30.         }
  31.         //////////////////////////////////////////////////////
  32.     }
  33.    
  34.     private static String pad( int maxWidth, int num ) {
  35.         //pad num on left with blanks to width of maxWidth
  36.         String maxPad = "          ";
  37.         int idx = maxPad.length() - maxWidth + ("" + num).length();
  38.         return maxPad.substring( idx ) + num;
  39.     }
  40.     private static int readInt( String prompt, Scanner scan ) {
  41.         int i = 0;  // set return into method-global scope
  42.         // read until valid input given
  43.         while (true) {
  44.             System.out.println( prompt );
  45.             try {
  46.                 i = scan.nextInt();
  47.                 break;
  48.             }
  49.             catch( InputMismatchException e ) {
  50.                 String sink = scan.next();
  51.                 System.out.println(
  52.                     "invalid value: " + sink + "\n" +
  53.                     e.toString()
  54.                 );
  55.             }
  56.         }
  57.         return i;
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement