/* Number/Word Chart written by Keith Fenske Sunday, 28 April 2002 Copyright (c) 2002 by Keith Fenske. All rights reserved. This Java program prints a square chart filled with random numbers and a single repeated word (the author's name). The user is asked for the size of the chart. This program demonstrates nested "for" loops and the "switch" statement. */ import cs1.Keyboard; // import Lewis/Loftus keyboard class // http://duke.csc.villanova.edu/jss/keyboard.html public class NumberWord { public static void main(String[] args) { int column, row; // index variables in "for" loop int length; // number of digits to generate int number; // random number of correct length int size; // size of the chart System.out.print("\nWhat is the size of the chart? (1 to 10) "); size = Keyboard.readInt(); if ((size < 1) || (size > 10)) { System.out.println("Sorry, but your size " + size + " must be from 1 to 10."); } else { for (row = 0; row < size; row ++) { printLine(size); // print horizontal line before row for (column = 0; column < size; column ++) { if (row == column) System.out.print("|Keith"); else { // generate random length from 1 to 5 digits length = 1 + (int) (Math.random() * 5); // now generate a new random number of the correct length, // and print it differently depending upon the length switch (length) { case 1: // 1-digit numbers from 0 to 9 number = (int) (Math.random() * 10); System.out.print("| (" + number + ") "); break; case 2: // 2-digit numbers from 10 to 99 number = 10 + (int) (Math.random() * 90); System.out.print("| " + number + "* "); break; case 3: // 3-digit numbers from 100 to 999 number = 100 + (int) (Math.random() * 900); System.out.print("| " + number + " "); break; case 4: // 4-digit numbers from 1000 to 9999 number = 1000 + (int) (Math.random() * 9000); System.out.print("|$" + number); break; case 5: // 5-digit numbers from 10000 to 99999 number = 10000 + (int) (Math.random() * 90000); System.out.print("|" + number); break; default: System.out.println("error in main(): length = " + length); } } } // end column System.out.println("|"); // end output line } // end row printLine(size); // print last horizontal line } } // end main() /* printLine() method This method prints one horizontal line in the chart, with the number of columns given by the caller. */ private static void printLine(int columns) { int i; // index variable in "for" loop for (i = 0; i < columns; i ++) System.out.print("+-----"); System.out.println("+"); // end output line } }