Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.InputMismatchException;
- import java.util.Scanner;
- public class PrintGrid
- {
- public static void main( String[] args ) {
- Scanner scan = new Scanner( System.in );
- int rows = readInt(
- "How many rows (positive integer)?", scan
- );
- int cols = readInt(
- "How many columns (positive integer)?", scan
- );
- print( rows, cols );
- }
- private static void print( int rows, int cols ) {
- // display width to which each number should be padded
- int maxWidth = 2 + ("" + rows*cols).length();
- // THIS IS THE PART YOU WANT...REST IS PROOF-OF-CONCEPT
- for (int i = 1; i <= rows; i++) {
- for (int j = 0; j < cols; j++) {
- // i + j*rows with i running from 1 to rows and
- // j running from 0 to cols - 1 is the answer
- System.out.print( pad( maxWidth, i + j*rows ));
- }
- System.out.println(); // start next row
- }
- //////////////////////////////////////////////////////
- }
- private static String pad( int maxWidth, int num ) {
- //pad num on left with blanks to width of maxWidth
- String maxPad = " ";
- int idx = maxPad.length() - maxWidth + ("" + num).length();
- return maxPad.substring( idx ) + num;
- }
- private static int readInt( String prompt, Scanner scan ) {
- int i = 0; // set return into method-global scope
- // read until valid input given
- while (true) {
- System.out.println( prompt );
- try {
- i = scan.nextInt();
- break;
- }
- catch( InputMismatchException e ) {
- String sink = scan.next();
- System.out.println(
- "invalid value: " + sink + "\n" +
- e.toString()
- );
- }
- }
- return i;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement