换行并分页打印机的输入字符串

时间:2015-05-10 20:30:00

标签: java string printing

以下是问题陈述:

  

重构打印机的字符串。打印机只能在页面上打印40行,页面只能容纳20行。页面底部应包含" Page X"其中X是页码。页码从1开始。

到目前为止,这是我的代码:

import java.lang.String;

public class Problem11
{
    /**
     * Creates a new instance of <code>Problem11</code>.
     */
    public Problem11()
    {
    }
    public static void main(String[] args)
    {
        String phrase = "The quick brown fox jumps over the lazy dog who bit him on the butt.";
        //String phrase = "1234567890123456789012345678901234567890123456789012345678901234567890";
        int max_lines = 20;
        int max_characters = 40;
        int page_num = 0;
        int carriage_ret = 0;
        int start_position = 10;
        int end_position = 0;
        String printline = "";

        do
        {
            start_position = carriage_ret;
            end_position = start_position + max_characters;
            carriage_ret = findSpace(phrase, start_position, end_position) + start_position;

            System.out.println("You are on line 37.");

            if ( carriage_ret > phrase.length())
            {
                carriage_ret = phrase.length();
                break;
            }
            //else
            //{
            //    carriage_ret = findSpace(phrase, start_position, end_position) + start_position;
            //}

            printline = phrase.substring(start_position, carriage_ret);
            System.out.println(printline);

            System.out.println(carriage_ret + "");

            if ( start_position > phrase.length())
            {
                break;
            }
        } while (true);

    }

    private static int findSpace( String phrase, int start, int end )
    {
        String tempString = " ";
        int result = 0;

        if ( end > phrase.length())
        {
            end = phrase.length();
          }

          tempString = phrase.substring(start,end);

          result = tempString.lastIndexOf(" ");
          System.out.println(tempString);

          return result;
    }
}

它编译,但我没有得到要求的结果。 我得到一个无限循环,整个短语没有在第40个字符处分解。

1 个答案:

答案 0 :(得分:0)

我认为你有一个无限循环的原因是这行代码:

        } while (true);

您在40个字符后没有获得回车的原因似乎是您正在执行:

System.out.println(tempString);

findSpace方法的内部,它没有考虑在40个字符限制之前计算为最后一个空格的位置。