Aligning in java

Advertisements

I am trying to print the multiplication table using java 19.0.2, using the following code:

public class MultiplicationTable {
    public static void main(String[] args) {
        for (int i = 1; i < 11; i++) {
            System.out.println(" 5 * "+ String.format("%2n", i) + " = " + (5*i)); 
        }
    }
}

And I get this error output:

Exception in thread "main" java.util.IllegalFormatWidthException: 2
        at java.base/java.util.Formatter$FormatSpecifier.checkText(Formatter.java:3313)
        at java.base/java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2996)
        at java.base/java.util.Formatter.parse(Formatter.java:2839)
        at java.base/java.util.Formatter.format(Formatter.java:2763)
        at java.base/java.util.Formatter.format(Formatter.java:2717)
        at java.base/java.lang.String.format(String.java:4150)
        at HelloWorld.main(HelloWorld.java:4)

Can someone help?

>Solution :

To format an integer to a width of 2, you should use "d" instead of
"n".

You need to change system.out print line of code from

System.out.println(" 5 * "+ String.format("%2n", i) + " = " + (5*i)); 

To

System.out.println(" 5 * " + String.format("%2d", i) + " = " + (5 * i));

Your final code will be :

public class MultiplicationTable {
    public static void main(String[] args) {
        for (int i = 1; i < 11; i++) {
            System.out.println(" 5 * " + String.format("%2d", i) + " = " + (5 * i));
        }
    }
}

Result :

5 *  1 = 55 *  2 = 10
 5 *  3 = 15
 5 *  4 = 20
 5 *  5 = 255 *  6 = 30
 5 *  7 = 35
5 *  8 = 40
 5 *  9 = 45
5 * 10 = 50

Leave a ReplyCancel reply