【问题标题】:Using the printf is giving me unaligned columns使用 printf 给了我未对齐的列
【发布时间】:2015-11-16 02:24:42
【问题描述】:

我试图让我的程序以简洁的格式打印出数据,数据与列对齐。我尝试在我的类的 toString 方法中使用 String.format,但它根本没有对齐。应该怎么改?

package p01;

import java.text.DecimalFormat;

public class Book
{
DecimalFormat formatter=new DecimalFormat("##0.00");


private int bookNumber;
private String title;
private String author;
private int numberOfPages;
private String ISBN;
private double price;

public Book(int bookNumber, String title, String author, int numberOfPages,String ISBN, double price)
{
    super();
    this.bookNumber = bookNumber;
    this.title = title;
    this.author = author;
    this.numberOfPages = numberOfPages;
    this.ISBN = ISBN;
    this.price = price;
}

private final int validBookNumber(int bookNumber)
{
    if(bookNumber<0||bookNumber>7)
    {
        throw new IllegalArgumentException("The book number must be from 1 to 7");
    }
    return bookNumber;
}

private final String validTitle(String title)
{
    if (title==null)
    {
        throw new IllegalArgumentException("The title can't be null");
    }
    title.trim();
    if(title.length()==0)
    {
        throw new IllegalArgumentException("The title can't be blank");
    }
    return title;
}

private final String validAuthor(String author)
{
    if (author==null)
    {
        throw new IllegalArgumentException("The name of the author can't be null");
    }
    author.trim();
    if(author.length()==0)
    {
        throw new IllegalArgumentException("The name of the author can't be blank");
    }
    return author;
}
private final String validISBN(String ISBN)
{
    if (ISBN==null)
    {
        throw new IllegalArgumentException("The ISBN can't be null");
    }
    ISBN.trim();
    if(ISBN.length()==0)
    {
        throw new IllegalArgumentException("The ISBN can't be blank");
    }
    return ISBN;
}
private final int validNumberOfPages(int numberOfPages)
{
    if(numberOfPages<=0)
    {
        throw new IllegalArgumentException("The number of pages can't be less than 0");
    }
    return numberOfPages;
}
private final double validPrice(double price)
{
    formatter.format(price);
    if(price<=0)
    {
        throw new IllegalArgumentException("The price can't be less than 0");
    }
    return price;
}

public boolean equals(Object obj)
{
    if(obj != null && obj instanceof Book)
    {
        Book tempBook=(Book)obj;
        if(ISBN.equalsIgnoreCase(tempBook.ISBN))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}
public String toString()
{
    String str;
    str=String.format("%-4s %-11s %-11s %-11s %-11s %-3s",validBookNumber(bookNumber),validTitle(title),validAuthor(author),
                        validPrice(price), validNumberOfPages(numberOfPages), validISBN(ISBN));//I used the String formatter here
    return str;
}

}

package p01;
public class MJE_AB_List_Driver01
{

public static void main(String[] args)
{
    MJE_AB_List<Book>myBookList=new MJE_AB_List<Book>();
    Book book1=new Book(1,"To kill a Mocking Bird", "Harper Lee",336,"9780061120084", 16.99);
    Book book2=new Book(2,"Fahrenheit 451", "Ray Bradbury",256," 9781451673319", 15.99);
    Book book3=new Book(3,"1984", "George Orwell",304,"9780452262935", 16.00);
    Book book4=new Book(4,"Fight Club", "Chuck Palahniuk",224,"0-393-03976-5", 14.95);
    Book book5=new Book(5,"Invisible Monsters", "Chuck Palahniuk",304,"9780061120084", 16.99);
    Book book6=new Book(6,"Frankenstein", "Mary Shelly",256,"9781593081157", 6.95);
    Book book7=new Book(7,"The Grapes of Wrath", "John Steinbeck",528,"9780143039433", 17.00);

    myBookList.add(book1);
    myBookList.add(book2);
    displayList(myBookList);




}
public static void displayList(ParticularListInterface list)//This displays the list
{
    String headerString="Index    Book#    Title     Author     Price   Pages   ISBN";
    System.out.println(headerString +"\n");
    for(int index=0;index<list.size(); index++)
    {

        System.out.println(index+ " "+list.get(index));
    }
}

}

这是我得到的输出

Index    Book#    Title     Author     Price   Pages   ISBN

0 1    To kill a Mocking Bird Harper Lee  16.99       336            9780061120084
1 2    Fahrenheit 451 Ray Bradbury 15.99       256          9781451673319

这是我在西蒙回答后的输出

Index    Book#    Title      Author     Price   Pages   ISBN

0  1    To kill a Mocking Bird                                       Harper Lee                16.99       336         9780061120084
1  2    Fahrenheit 451                                               Ray Bradbury              15.99       256          9781451673319

【问题讨论】:

    标签: java alignment printf


    【解决方案1】:

    您数据中的标题/作者值似乎比您在String.format() 调用中分配的空间长。将长度从 11 增加到更高的值,例如:

    "%-4s %-40s %-25s %-11s %-11s %-3s"
    

    【讨论】:

    • 我尝试使用它,但使用后它仍然未对齐。我在上面的问题中有打印的内容
    • 现在你有一个不同的问题 - 标题行不匹配。使用相同的字符串格式打印标题行的列。
    • 我都改成同一个格式了,但是书号后面都没有对齐
    • 我最后的建议是确保列宽至少足够长以容纳标题名称。 (例如,将 Book# 的宽度从“%-4s”更改为“%-6s”)。在 String.format() 之外编写“索引”也可能是一个问题。
    【解决方案2】:

    格式字符串中的宽度是最小个字符,因此值将被填充到至少那个宽度,但如果它们更长,则将输出整个值。也就是说,除非您使用精度值指定 最大 个字符,例如:

    String.format("%-4s %-11.11s %-11.11s %-11.11s %-11.11s %-3s");
    

    这会将第 2 到第 5 个值截断为 11 个字符。但是请注意,它就是这样做的,只是去掉了值,所以"To Kill a Mockingbird" 变成了"To Kill a M",这可能是也可能不是你想要的。您可以增加宽度(正如 Simon 建议的那样)和精度,或者自己进行截断并添加省略号或其他内容,例如:

    if (title.length() > 11)
        title = title.substring(0, 10) + "\u2026";
    

    【讨论】:

    • 我已经尝试寻找有关如何增加宽度的信息,但我都不清楚
    • 格式中的宽度?这只是 % 和标志之后的第一个数字(如果您有其中一个,还有参数编号),所以在您的情况下是 11。将 11 更改为更大的值以增加最小宽度(并修复您的标题,尽管我会修改标题打印以使用相同的格式字符串,然后如果您修改另一个,则不必修改)。这是格式化字符串语法的reference。
    猜你喜欢
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 2021-03-03
    • 1970-01-01
    相关资源
    最近更新 更多