// TrianglePrinting.java // A solution to CS 5JA assignment 4, part 2, Winter 2009 // cmc, updated 2/9/09 (from Deitel instructor solutions) import java.util.Scanner; public class TrianglePrinting { public static void main( String args[] ) { int row, column, space; char c; int size = 0; final int MIN = 1; Scanner input = new Scanner(System.in); // get size, and insure it is an int in the proper range do { System.out.printf("Enter triangle size: "); if (input.hasNextInt()) { size = input.nextInt(); if (size < MIN) System.out.println("minimum size is " + MIN); } else { String badData = input.next(); System.err.println("ERROR - not integer: " + badData); } } while(size < MIN); // get character to print System.out.printf("Enter character: "); c = input.next().charAt(0); // one row is printed at a time for ( row = 1; row <= size; row++ ) { // part a (leftmost triangle) for ( column = 1; column <= row; column++ ) System.out.print( c ); for ( space = 1; space <= size - row; space++ ) System.out.print( ' ' ); System.out.print( ' ' ); // extra space to separate triangles // part b for ( column = size; column >= row; column-- ) System.out.print( c ); for ( space = 1; space < row; space++ ) System.out.print( ' ' ); System.out.print( ' ' ); // part c for ( space = 1; space < row; space++ ) System.out.print( ' ' ); for ( column = size; column >= row; column-- ) System.out.print( c ); System.out.print( ' ' ); // part d for ( space = size; space > row; space-- ) System.out.print( ' ' ); for ( column = 1; column <= row; column++ ) System.out.print( c ); // advance to next print line for next row System.out.println(); } } }