Search code examples
javaescapingtap

How do i continuously escape \t in java?


I searched for same questions.(How do I escape a string in Java?) but i can't solve my problem.

part of source code System.out.println("year : "+year+"\t"+"rate_year : "+rate_year+"\t"+"rate_month : "+rate_month);

but when i print that . . . year : 10 rate_year : 0.4 rate_month : 0.03333333333333333

This prints first "\t" why all "\t"s are not adapted???


Solution

  • A "\t" advances to the next tab stop. If one changes the text description slightly, notice the alignment:

    System.out.println("year : "+year+"\t"+"rate_year : "+rate_year+"\t"+"rate_month : "+rate_month);
    System.out.println("year : "+year+"\t"+"ry : "+rate_year+"\t"+"rm : "+rate_month);
    

    Output:

    year : 10   rate_year : 0.4 rate_month : 0.333333    
    year : 10   ry : 0.4        rm : 0.333333
    

    I believe the issue is simply where the tab column is falling.

    On a different note, if the goal is column alignment, it might be better to use printf and specific column sizes. See, e.g., this answer on formatting with \t

    Example:

    for (int i = 0; i < 12; ++i) {
            System.out.printf("year : %3d rate_year : %6f rate_month : %-6f\n", 
                    i,
                    rate_year,
                    rate_month);
    }
    

    Output:

    year :   8 rate_year : 0.400000 rate_month : 0.333333  
    year :   9 rate_year : 0.400000 rate_month : 0.333333      
    year :  10 rate_year : 0.400000 rate_month : 0.333333  
    year :  11 rate_year : 0.400000 rate_month : 0.333333