Justify text in Java

后端 未结 9 1380
闹比i
闹比i 2020-12-21 16:33

I have to read in an integer which will be the length of the succeeding lines. (The lines of text will never be longer than the length provided).

I then have to read

9条回答
  •  孤城傲影
    2020-12-21 17:20

    The hardest thing about this problem is defining "as evenly as possible".

    Your example:

     Hello__this__is__a_test_string
    

    ... makes all the longer gaps be at the left. Wouldn't:

     Hello__this_is__a_test__string
    

    ... fit the imprecise description of the problem better, with the longer gaps spread evenly through the output string?

    However, let's solve it so it gives the sample answer.

    • First you need to know how many extra characters you need to insert -- numNewChars == lengthWanted minus inputString.length()
    • Next you need to count how many gaps there are to distribute these new characters between -- call that numGaps -- it's the number of words minus one.
    • In each space you will insert either n or n+1 new spaces. n is numNewChars / numGaps -- integer division; rounds down.
    • Now, how many times do you need to insert n+1 new spaces instead of n? It's the remainder: plusOnes = numNewChars % numGaps

    That's all the numbers you need. Now using whatever method you've been taught (since this is evidently a homework problem, you don't want to use language features or libraries that haven't been covered in your lessons), go through the string:

    • For the first plusOnes spaces, insert n+1 spaces, in addition to the space that's already there.
    • For the remaining spaces, insert n spaces.

    One very basic method would be as follows:

    String output= "";
    for(int i=0; i

提交回复
热议问题