Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Class: CSC190
- * Project: hw7
- * Date: 2013, Oct 16
- * Author: Austin Holbrook <[email protected]>
- * Purpose: This program takes an input (n) between 1 and 13 and prints out 3
- * triangles of size n
- */
- import java.util.Scanner;
- class Triangle {
- int lines;
- public void setLines(int lines) {
- this.lines = lines;
- }
- int getTriangularNumber(int n) {
- return (n * (n+1)) / 2;
- }
- void plotLeftAlignedHorizontal() {
- for (int i = 1; i <= lines; i++) {
- for (int j = getTriangularNumber(i)-i+1; j <= getTriangularNumber(i); j++) {
- System.out.printf("%-3d", j); //the dash left aligns the values
- }
- System.out.println();
- }
- System.out.println();
- }
- void plotLeftAlignedVertical() {
- int lastNum = 0;
- for (int i = 1; i <= lines; i++) {
- for (int j = lines; j > lines-i; j--) {
- if (j == lines) {
- lastNum = i;
- System.out.printf("%-3d", lastNum);
- }
- else {
- lastNum += j;
- System.out.printf("%-3d", lastNum);
- }
- }
- System.out.println();
- }
- System.out.println();
- }
- void plotRightAlignedDiag() {
- int lastNum = 0;
- int times = 0;
- for (int i = lines; i >= 1; i--) {
- times++;
- //Print the leading space
- for (int j = 1; j <= lines-times; j++) {
- System.out.print(" ");
- }
- for (int j = lines; j > lines-times; j--) {
- if (j == lines) {
- lastNum = i;
- System.out.printf("%3d", lastNum);
- }
- else {
- lastNum += j+1;
- System.out.printf("%3d", lastNum);
- }
- }
- System.out.println();
- }
- }
- }
- public class Runner {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- Triangle myTriangle = new Triangle();
- int lines; //Lines the triangle has
- //Validate input for lines
- while (true) {
- System.out.print("Enter lines (1 - 13): ");
- lines = sc.nextInt();
- if (lines >= 1 && lines <= 13) {
- myTriangle.setLines(lines);
- break;
- }
- System.out.println("You must enter a value between 1 and 13!");
- }
- myTriangle.plotLeftAlignedHorizontal();
- myTriangle.plotLeftAlignedVertical();
- myTriangle.plotRightAlignedDiag();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment