Home > database >  Aligning in java
Aligning in java

Time:02-02

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?

CodePudding user response:

In the original code, String.format("%2n", i) is not a valid format specifier. The %n format specifier is used to insert a newline character, not to format a number. To format a number with a specific width, you should use - instead, where 2 is the width.

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

In this code, String.format(" 5 * - = -", i, 5*i) creates a formatted string where - is used to format the two integer values i and 5*i with a width of 2 characters.

CodePudding user response:

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("-", 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("-", 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

  •  Tags:  
  • java
  • Related