0Pricing
Java Academy · Lesson

2D Utilities as a Helper Class (Refactor)

Refactor repeated 2D logic into a reusable helper. Expose static utilities for widths, aligned printing, averages, maxima and transpose. Use the helper from small demos.

Why Refactor

Why refactor into a helper? Avoid copy-paste, keep one source of truth, and make later lessons simpler. We will create a GradeUtil helper with static methods for widths, aligned printing, averages, maxima and transpose.

Helper Shell + Print

Create a static GradeUtil with widths and printAligned. Then, from main, call GradeUtil.printAligned(m) to print any jagged matrix with aligned columns.

public class Main {
  // Static helper with reusable utilities for 2D int matrices
  static class GradeUtil {
    // Compute per-column widths (jagged-aware)
    static int[] widths(int[][] m) {
      int maxCols = 0;
      for (int r = 0; r < m.length; r = r + 1) if (m[r].length > maxCols) maxCols = m[r].length;
      int[] w = new int[maxCols];
      for (int r = 0; r < m.length; r = r + 1) {
        for (int c = 0; c < m[r].length; c = c + 1) {
          int len = Integer.toString(m[r][c]).length();
          if (len > w[c]) w[c] = len;
        }
      }
      for (int c = 0; c < w.length; c = c + 1) if (w[c] < 1) w[c] = 1;
      return w;
    }

    // Print matrix with aligned columns
    static void printAligned(int[][] m) {
      int[] w = widths(m);
      for (int r = 0; r < m.length; r = r + 1) {
        String line = "";
        for (int c = 0; c < m[r].length; c = c + 1) {
          String s = Integer.toString(m[r][c]);
          while (s.length() < w[c]) s = " " + s;
          line = line + s + (c + 1 < m[r].length ? " " : "");
        }
        System.out.println(line);
      }
    }
  }

  public static void main(String[] args) {
    // Demo: build a small jagged matrix and print it via the helper
    int[][] m = {
      {1, 23, 456},
      {7, 8},
      {90, 12, 3, 4}
    };
    System.out.println("Aligned print via GradeUtil:");
    GradeUtil.printAligned(m);
  }
}

All lessons in this course

  1. 2D Array Basics & Nested Iteration
  2. Jagged Arrays & Table Formatting
  3. Row/Column Maxima, Transpose & Formatting
  4. 2D Mini-Project: Gradebook
  5. 2D Utilities as a Helper Class (Refactor)
  6. 2D Data Cleaning & Validation
← Back to Java Academy