创建一个包含列标题的表并排列值

时间:2015-04-30 02:22:59

标签: java alignment

我试图在不使用JTable或任何其他表函数(就像文本)的情况下打印出一个表。到目前为止,我能够打印出值,但似乎无法使它们正确排列。我正在尝试使用制表符,但有些值比其他值长,这使得它很难。任何提示将不胜感激。

package costisnoobjectfinalproject;

import java.text.NumberFormat;
import java.util.Scanner;

public class CostIsNoObjectFinalProject {

    public static void main(String[] args) {

        String customerName;
        String carCode;
        int numOfDays;
        Scanner response = new Scanner(System.in);
        NumberFormat money = NumberFormat.getCurrencyInstance();

        String[] columnHeaders = {"Description", "Daily Fee", "Code"};
        String[] cars = {"1967 Ford Mustang", "1922 Ford Model T", "2008 Lincoln Continental", "2002 Lexus", "2007 BMW", "1910 Mercer Runabout", "2009 Mercedes Benz", "1930 Cadillac V-16"};
        double[] dailyFee = {65.0, 95.0, 135.0, 140.0, 160.0, 165.0, 200.0, 205.0};
        String[] carType = {"A", "A", "L", "L", "L", "A", "L", "A"};
        boolean[] alreadyRented = {false, false, false, false, false, false, false, false};

        System.out.println("Welcome to the Antique/Luxury Car Lot! First, let's start with some information.");
        System.out.println("Please enter your name: ");
            customerName = response.nextLine();
        System.out.println("Thank you. Which kind of car would you like to rent? (L for luxury, A for Antique): ");
            carCode = response.nextLine();
        System.out.println("How many days did you want to rent this car?: ");
            numOfDays = response.nextInt();

        for(int count = 0; count < cars.length ; count++) {
            System.out.println(cars[count] + "\t\t" + money.format(dailyFee[count]) + "\t" + carType[count] + "\t" + alreadyRented[count]);
        } //end for
    } // end main

} // end class

此代码的结果如下所示:

1967 Ford Mustang       $65.00  A   false
1922 Ford Model T       $95.00  A   false
2008 Lincoln Continental        $135.00 L   false
2002 Lexus      $140.00 L   false
2007 BMW        $160.00 L   false
1910 Mercer Runabout        $165.00 A   false
2009 Mercedes Benz      $200.00 L   false
1930 Cadillac V-16      $205.00 A   false

1 个答案:

答案 0 :(得分:0)

输出中的标签导致列未对齐。较长的文本值将下一列推送到后面的Tab Stops。

我通常做的事情:

  1. 查找每列中字符数最多的字符串
  2. 为每个字符串填充足够的空格以匹配其各自列的最大字符数(包括标题行字符串)
  3. 一旦所有填充到相同长度的行打印行和星星,er列将对齐
  4. 填充将取代标签,如果你喜欢,你可以只用一个字符分隔列

    左对齐字符串末尾的列填充,右对齐填充开头,以填充开头和结尾之间的填充。

    要打印填充标题,只需在输入for循环之前使用与循环中相同的格式字符串放置打印