Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Aligning in java

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading