123456789101112131415161718192021222324252627282930313233343536
  1. public class TableUtilities {
  2. public static String getSmallMultiplicationTable() {
  3. return getMultiplicationTable(5);
  4. }
  5. public static String getLargeMultiplicationTable() {
  6. return getMultiplicationTable(10);
  7. }
  8. /**
  9. * The two above methods, small/large MultiplicationTable, call on the
  10. * getMultiplicationTable to produce the desired result.
  11. *
  12. * Originally, the same code was used for each method, and the
  13. * "tableSize" parameter was just the req'd table size (ie. 5).
  14. *
  15. * However, since each method returns the same format, calling on
  16. * getMultiplicationTable becomes more efficient and cuts down on
  17. * repeat code.
  18. *
  19. */
  20. public static String getMultiplicationTable(int tableSize) {
  21. StringBuilder multiTable = new StringBuilder();
  22. // nested for loop
  23. for (int i = 1; i <= tableSize; i++) {
  24. for (int j = 1; j <= tableSize; j++) {
  25. multiTable.append(String.format("%3d |", i * j));
  26. }
  27. multiTable.append("\n");
  28. }
  29. return multiTable.toString();
  30. }
  31. }