java help?
Write a method called padString which takes in arguments: String stringToPad, char padCharacter, int paddedLength. The method should return a string that contains the stringToPad but is padded on the left side with the padCharacter to the number of characters indicated by paddedLength. For example, invoked as padString(“12345”, ‘z’, 9) should return “zzzz12345”.
2 Answers
- brilliant_movesLv 73 weeks ago
Hi, isaac.
Here's a solution to this question. The only tricky bit is that in the example given, you don't add 9 z's, instead you add (9 - 5) z's. The 5 refers to the length of "12345" in the question. Then you add the padCharacter *before* the stringToPad.
public class IsaacsStringPadder {
public String padString(String stringToPad, char padCharacter, int paddedLength) {
String ans = stringToPad;
for (int i=0; i<paddedLength-stringToPad.length(); i++) {
ans = padCharacter + ans;
}
return ans;
}
public static void main (String[] args) {
IsaacsStringPadder padder = new IsaacsStringPadder();
String s = "Isaac should do his own homework!"; // sample text
System.out.println (padder.padString (s, '@', 40));
}
}
- Anonymous3 weeks ago
Homework Section >>>>>>>>>