user9884364
user9884364

Reputation: 3

JAVA Printing issues using printf

I have some issues with printing my code. I want my result to be aligned neatly but it isn't like that. It would be very grateful if someone could help me with the issue.

my code is as follows :

public static void main(String[] args) {
    for(int j=1 ; j<=31;j++) {
        System.out.printf("%10d",j);
        if(j%7==0) {
            System.out.println();
        }

    }
}

the result I get to see on my screen as belows

enter image description here

Upvotes: 0

Views: 84

Answers (2)

mentallurg
mentallurg

Reputation: 5207

Your code is correct. But you should use MONOSPACED (fixed width) font like Courier or Lucida Console in your terminal / console:

  • you use not monospaced font in your OS terminal
  • or you use not monospaced font in the console of your IDE
  • or you forward your output to file that you view in some editor again with not monospaced font
  • or something similar with not monospaced font

Upvotes: 1

rodridevops
rodridevops

Reputation: 1987

According to Formatting Numeric Print Output

Format specifiers begin with a percent sign (%) and end with a converter. The converter is a character indicating the type of argument to be formatted. In between the percent sign (%) and the converter you can have optional flags and specifiers

In this case:

  1. % is format syntax mandatory prefix.
  2. - is the flag for Left-justified.
  3. 10 means ten characters in width, with leading zeroes as necessary.
  4. d, A decimal integer.

So your main method should be:

public class Tst {
    public static void main (String[] args)
    {
        for(int j=1 ; j<=31;j++) {
            System.out.printf("%-10d",j);
            if(j%7==0) {
                System.out.println();
            }

        }
    }
}

Giving the resulting output:

enter image description here

Upvotes: 1

Related Questions