From 3d7f4d6817987f22550a54fde9f0a829ec5bf432 Mon Sep 17 00:00:00 2001 From: Rob Hallam <0504004h@student.gla.ac.uk> Date: Tue, 19 Sep 2023 22:31:38 +0100 Subject: [PATCH] (feat) Lab 6 Exercise 8 - left padding a string --- week1.java | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/week1.java b/week1.java index 39adbd5..d99d9eb 100644 --- a/week1.java +++ b/week1.java @@ -255,6 +255,7 @@ class Lab6 extends Lab { new six5(); new six6(); new six7(); + new six8(); } /** @@ -333,6 +334,56 @@ class Lab6 extends Lab { } } + /** + * Exercise 8 - String pad with specified character + */ + class six8 extends Exercise { + public six8() { + super(8); + describeStringPadding("NoNeed", 4, '!'); + describeStringPadding("Simon", 10, '@'); + describeStringPadding("Zaphod Beeblebrox", 42, '?'); + // describeStringPadding("Unicode", 10, '🤯'); aww + } + + /** + * Print for display what we're padding and the result + * + * @param toPad The string to pad eg "Simon" + * @param length Desired length + * @param padChar Character to pad with + */ + public void describeStringPadding(String toPad, int paddedLength, char padChar) { + System.out.println(String.format("Padding '%s' to length %d using padding character: %s", + toPad, paddedLength, padChar)); + System.out.println(stringLPad(toPad, paddedLength, padChar)); + } + + /** + * (Left-)pad a string with the specific character + * + * @param toPad The string to pad eg "Simon" + * @param length Desired length + * @param padChar Character to pad with + * @return The padded result + */ + public String stringLPad(String toPad, int paddedLength, char padChar) { + // early out - return unmodified + if (toPad.length() >= paddedLength) { + return toPad; + } + // note that we could do this with String.repeat(), but since this is in the 'Loops' + // part of the lab, we should probably do this with a loop + // String paddedString = String.valueOf(padChar) + toPad; + String paddedString = toPad; + while (paddedString.length() < paddedLength) { + paddedString = String.valueOf(padChar) + paddedString; + } + return paddedString; + } + + } + /* TOASK - is there a better way of returning multiple values in Java? à la python, ie: return (quotient, remainder) */ @@ -391,6 +442,8 @@ class Lab6 extends Lab { /* 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 + + TODO: handle multi-digit numbers */ System.out.println(String.format("")); int spaces = num;