Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java printing string with fixed width

I have to write a code in Java that will take a String and put a certain number of characters on each line (the fixed width). I will also have to put extra spaces in to fill in any extra spots, like if four words only equal 23 characters and the line calls for 25, so I'd need to input two extra spaces. This is for a beginning class, so it just needs to be as basic as possible. So far, what I have is:

public static void print (String[] theWords, int width) {

  int start = 0, end = 0, lineCounter = 0;
  int[] gaps;

Where do I go from here?

like image 547
Lucille Avatar asked Mar 31 '15 14:03

Lucille


People also ask

How do I print a fixed size?

Print a sheet on a specified number of pagesOn the Page Layout tab, select Page Setup. On the Page tab, select the Fit To check box. In the Pages wide by and Tall boxes, enter the number of pages on which you want to print the sheet. On the File menu, click Print.

What is %s and %D in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

What is %- 5d in Java?

"%5d" Format a string with the required number of integers and also pad with spaces to the left side if integers are not adequate. "%05d" Format a string with the required number of integers and also pad with zeroes to the left if integers are not adequate.


1 Answers

As you have not written what you have done so far, neither how the expected input looks like and what output do you expect. The answer will be weak as well

At least one simple example. For more information about the format string have a look into the related javadoc

System.out.printf("%-25s : %25s%n", "left justified", "right justified");
System.out.printf("%25s : %-25s%n", "right justified", "left justified");
// if you want to get a String
String s1 = String.format("%-25s : %25s%n", "left justified", "right justified");
String s2 = String.format("%25s : %-25s%n", "right justified", "left justified");
like image 124
SubOptimal Avatar answered Nov 15 '22 00:11

SubOptimal