如何在java中获得正确的空间填充

时间:2017-02-01 01:17:55

标签: java string formatting

我试图将所有名称和数字整齐地对齐,间距为10个字符,但由于某种原因格式化了。

我使用.trim()去除空格,我尝试使用,作为分隔符,但格式仍然搞砸了。

import java.util.Scanner;
import java.io.File;

public class StraightAs {

    public static void main(String[] args) throws Exception {
        if (args.length == 0) {
            // TODO: the line of code below is a checkstyle violation.
            // Figure out what the violation is and what you can do to fix it.
            // You can find instructions on how to run checkstyle in the
            // homework instructions
            System.out.println("Welcome to Java. Are you ready to take on the challenge?\nMake sure you read and fully understand the provided instructions and the comments in this file to ensure you get full credit for your work.");



            showUsage("");
        } else if (args.length == 3) {
            // The code you write in processGrades will be called when your
            // program is run with two additional command line arguments, for
            // example: java StraightAs myfile.csv myseparator
            processGradesFromFile(args[0], args[1], args[2]);
        } else {
            showUsage(args[0]);
        }
    }


    /**
     * This method will create a grade histogram from a given csv file.
     * In your implementation, you need to read in the data, parse it as a CSV
     * formatted file with the provided data separator string, and output the
     * processed data to your terminal window. See the @param tags below for
     * more details on each parameter
     *
     * @param filename      the filename of the CSV file to read and process
     *                      data from
     * @param separator     the CSV file's given data separator. This is the
     *                      string constant that your program should use to
     *                      split each line in the CSV file into data fields
     *                      for parsing
     * @param displayMode   the type of output your program should show. We
     *                      define three modes: TABLE, HIST, and BOTH. See the
     *                      homework instructions for information on each of
     *                      these modes
     * @throws Exception    Don't worry about what this means yet. You'll learn
     *                      about exceptions later in the course =)
     */
    public static void processGradesFromFile(
            String filename, String separator, String displayMode)
        throws Exception {
        // TODO implement me!
        Scanner scan = new Scanner(new File(filename));



        while(scan.hasNextLine()){

            System.out.printf("%10s\n", scan.nextLine().trim());

        }

        scan.close();

        if (displayMode == "TABLE"){

        } else if (displayMode == "HIST") {





        } else if (displayMode == "BOTH"){

        }


    }

1 个答案:

答案 0 :(得分:0)

<强> EDITED

你不允许表格吗?用&#34; \ t&#34;?当然,您更喜欢它而不是在它们之间添加10个空格。添加10个空格将失去基于名称长度的格式

这将在你的身上发生

    while(scan.hasNextLine())
    {
        String[] splitted = scan.split(",");

        for(int i = 0; i<splitted.length; i++)
        {
            System.out.printf("%s\t\n", splitted[i].trim());
        }
        System.out.println(""); //for new line, or else print("\n");
    }

完整格式

import java.util.Scanner;
import java.io.File;

public class StraightAs 
{
    public static void main(String[] args) throws Exception 
    {
        if (args.length == 0) 
        {
            // TODO: the line of code below is a checkstyle violation.
            // Figure out what the violation is and what you can do to fix it.
            // You can find instructions on how to run checkstyle in the
            // homework instructions

            System.out.println("Welcome to Java. Are you ready to take on the challenge?\nMake sure you read and fully understand the provided instructions and the comments in this file to ensure you get full credit for your work.");

            showUsage("");
        }

        else if (args.length == 3) 
        {
            // The code you write in processGrades will be called when your
            // program is run with two additional command line arguments, for
            // example: java StraightAs myfile.csv myseparator
            processGradesFromFile(args[0], args[1], args[2]);
        }

        else 
        {
            showUsage(args[0]);
        }
    }


    /**
     * This method will create a grade histogram from a given csv file.
     * In your implementation, you need to read in the data, parse it as a CSV
     * formatted file with the provided data separator string, and output the
     * processed data to your terminal window. See the @param tags below for
     * more details on each parameter
     *
     * @param filename      the filename of the CSV file to read and process
     *                      data from
     * @param separator     the CSV file's given data separator. This is the
     *                      string constant that your program should use to
     *                      split each line in the CSV file into data fields
     *                      for parsing
     * @param displayMode   the type of output your program should show. We
     *                      define three modes: TABLE, HIST, and BOTH. See the
     *                      homework instructions for information on each of
     *                      these modes
     * @throws Exception    Don't worry about what this means yet. You'll learn
     *                      about exceptions later in the course =)
     */

    public static void processGradesFromFile(
            String filename, String separator, String displayMode)
        throws Exception 
    {

        // TODO implement me!

        Scanner scan = new Scanner(new File(filename));

        while(scan.hasNextLine())
        {
            String[] splitted = scan.split(",");

            for(int i = 0; i<splitted.length; i++)
            {
                System.out.printf("%s\t\n", splitted[i].trim());
            }
            System.out.println(""); //for new line, or else print("\n");
        }

        scan.close();

        if (displayMode.equalsIgnoreCase("TABLE"))
        {
        } 

        else if (displayMode.equalsIgnoreCase("HIST")) 
        {
        }

        else if (displayMode.equalsIgnoreCase("BOTH"))
        {
        }
    }
}

END OF EDIT

以前的答案

为什么不把空字符串放在+&#34; N&#34;在扫描线之前的空间,以达到您想要的格式? :)

    while(scan.hasNextLine())
    {
        System.out.printf("%10s%s\n", "", scan.nextLine().trim());
    }

    //%10s to add 10 space
    //%s for your scanned nextLine()
    //.trim() to trim your input