I recently started to learn java, and in my java class I have to make a method in which it prints out in my main java class, text to the left, centered, and to the right. However I want to do this without the use of printf.
This is my text:
MyJavaUtils.formatText("This is my text left justified", 'l', 38);
MyJavaUtils.formatText("This is my text right justified", 'r', 38);
MyJavaUtils.formatText("This is my text centred", 'c', 38);
System.out.println("----------------------------------------");
MyJavaUtils.formatText("This is also left justified", 'l', 38);
MyJavaUtils.formatText("This is also right justified", 'r', 38);
MyJavaUtils.formatText("This is also centred", 'c', 38);
System.out.println("----------------------------------------");
MyJavaUtils.formatText("Also left", 'l', 18);
MyJavaUtils.formatText("Also right", 'r', 18);
MyJavaUtils.formatText("Also centred", 'c', 18);
System.out.println("----------------------------------------");
My method so far:
public static void formatText(String text, char justified, int wide) {
int space = wide - text.length();
for (int num = 0; num < space; ++num) {
System.out.print(" ");
}
System.out.println(text);
}
}
However this code prints every single line of text to the right side. The amount of extra spaces is correct, but I don't want every line to print to the right side. Like the text suggests, the text left justified should be to the left, right to the right, and centered is well, centered. I'm unsure of how to do all of this in one method.
output should look like this:
>This is my text left justified <
> This is my text right justified<
> This is my text centred <
However I'm not quite sure how I would be able to print out to the left, right and center without the use of printf. I am told to do this by finding the length of the string length of the text, which I have. However I'm not sure how to apply it to print out the appropriate amount of spaces to pad the output to the correct number of characters. As well as when I do the center output I'm supposed to +1 space to the right if the amount of extra spaces is odd.
Any help or hints would be appreciate thanks!