瀏覽代碼

(feat) Lab 6 Exercise 8 - left padding a string

main
Rob Hallam 1 年之前
父節點
當前提交
3d7f4d6817
共有 1 個文件被更改,包括 53 次插入0 次删除
  1. +53
    -0
      week1.java

+ 53
- 0
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;


Loading…
取消
儲存