如何使用循环和StringBuilder修改String

时间:2014-02-23 21:45:47

标签: java

我正在尝试编写一个打印目录的程序,并开发必要的代码以读取章节名称和 输入“ * *”之前的页码。输出的String需要长度相同,左右对齐。

如何在标题和页码之间添加点,以便输出的每个标题的长度相同? setEntries方法是我尝试这样做的地方。这是我到目前为止开发的代码:

import java.util.ArrayList;
import java.util.List;

public class TocEntry
{
    ArrayList<String> entries = new ArrayList<String>( 100 );
    StringBuilder sb = new StringBuilder();

    public void setMinLength( int length )
    {
        minLength = length;
    } // end method setMinLength

    public void setEntries(ArrayList<String> list)
     {
        int count = 0;

        for( String i : list)
        {
            sb.append(i).append("\n");

            String str = (String) list.get(count);

            int len = str.length();

            if( len < minLength )
            sb.append(".");
            count++;
        }
    } // end method note

    public String toString()
    {
        return sb.toString();
    }

    private String chapterPageEntry;
    private int minLength;
}// end class TocEntry

import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;

public class Toc
{
    public static void main( String[] args )
    {
        int index = 0;
        int longestChapterName = 0;

        TocEntry contents = new TocEntry();
        List entries = new ArrayList();

        Scanner input = new Scanner( System.in );

        while( index < 3 )
        {
            System.out.println( "Enter chapter name: " );
            String chapterName = input.nextLine();

            if( chapterName.equals( "****" ) )
                break;

            System.out.println( "Enter starting page number of chapter: " );
            int chapterStartingPage = input.nextInt();

            String entry = chapterName + ".." + chapterStartingPage;
            entries.add( entry );

            int length = entry.length();
            longestChapterName = Math.max( length, longestChapterName );

            input.nextLine();
            index ++;
            System.out.print(entry);
        } // end while

        contents.setMinLength( longestChapterName );

        contents.setEntries( entries );

        System.out.print( contents.sb );

    } // end main

2 个答案:

答案 0 :(得分:2)

这是让你入门的一个问题:

int i = 0;
while( i < list.size() )
{
   if( list.get(i).length() < minLength )
      sb.append(".");
}

这个循环永远不会结束,因为i永远不会改变:它总是永远等于零。这导致java.lang.OutOfMemoryError

使用i++在循环中增加它。

答案 1 :(得分:1)

一般过程是获取标题字符串,将页码转换为字符串,然后从您希望TOC条目的总宽度中减去这两个字符串的长度。结果将是您需要在这两个字符串之间打印以获得该宽度的点数。

示例,假设您希望总宽度为40:

title: "Some Chapter"     length: 12
page: "42"                length: 2
number of dots = 40 - (12 + 2) = 26

title: "Another Chapter"  length: 15
page: "200"               length: 3
number of dots = 40 - (15 + 3) = 22

Some Chapter..........................42  <- 26 dots
Another Chapter......................200  <- 22 dots