Java printing string with fixed width

假装没事ソ 提交于 2019-12-11 03:12:22

问题


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?


回答1:


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");


来源:https://stackoverflow.com/questions/29370621/java-printing-string-with-fixed-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!