Parcourir la source

Implement Lab 6 Exercise 6 (number triangle)

I spotted a neat way of doing this before I had to head off so couldn't resist
main
Rob Hallam il y a 1 an
Parent
révision
fd1fd718f2
1 fichiers modifiés avec 34 ajouts et 0 suppressions
  1. +34
    -0
      week1.java

+ 34
- 0
week1.java Voir le fichier

@@ -250,6 +250,7 @@ class Lab6 extends Lab {
System.out.println(String.format("%n"));
new six3();
new six5();
new six6();
}

/**
@@ -286,6 +287,39 @@ class Lab6 extends Lab {
System.out.println(String.format("TODO / NOT IMPLEMENTED until we get stdin working"));
}
}
/**
* Produce a number triangle
*
* eg:
* 1
* 2 2
* 3 3 3
* 4 4 4 4
*/
class six6 extends Section {
public six6() {
super(6);
numberTriangle(8);
}
}

/**
* @param num Size of triangle
*/
public void numberTriangle(int num) {
/* Observations:
- for even-sized triangles, preceding number of spaces starts at n=rows and decrements
- for even-sized triangles even numbers have odd spaces and vice versa
*/
int spaces = num;
for (int i = 1; i <= num; i++) {
System.out.println(" ".repeat(spaces)
+ String.format("%s ", i).repeat(i)
+ " ".repeat(spaces-1)
);
spaces--;
}
}

public void writeTimesTable(int num, int limit) {
for (int i = 0; i < (limit + 1); i++) {


Chargement…
Annuler
Enregistrer