user1726910
user1726910

Reputation: 35

Formatting output in Java

I want to format the numbers so that it gets displayed in proper format. At the moment 1-12 left side is displaying correctly apart from 1 because it has moved into another space due to pushing the 8 into the format.

The Wrong outcome is shown below... The (-) act as spaces on here because I cant attach an image.

--1 * 8 = -8
-2 * 8 = 16
-3 * 8 = 24
-4 * 8 = 32
-5 * 8 = 40
-6 * 8 = 48
-7 * 8 = 56
-8 * 8 = 64
-9 * 8 = 72
10 * 8 = 80
11 * 8 = 88
12 * 8 = 96

The outcome I want is shown below... The (-) act as spaces on here because I cant attach an image.

--1 * 8 = --8
--2 * 8 = 16
--3 * 8 = 24
--4 * 8 = 32
--5 * 8 = 40
--6 * 8 = 48
--7 * 8 = 56
--8 * 8 = 64
--9 * 8 = 72
10 * 8 = 80
11 * 8 = 88
12 * 8 = 96

I appreciate if anyone can help me with this... has been driving me insane.

Here is my code so far:

  public class Main {

        public static void main(String [] args) {

            int end_value = 13;
            int result = 0;

            System.out.print("Enter a Number:");
            int num_input = BIO.getInt();

            for (int numberLoop = 1; numberLoop < end_value; numberLoop++) 
            {
                result = numberLoop * num_input;

                System.out.printf("%11s\n", numberLoop + " * " + num_input + 
                                                          " = " + result);
            }
        }
    }

Upvotes: 3

Views: 5699

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213203

You should apply formatting on individual elements : -

System.out.format("%3d * %4d = %5d\n", numberLoop, num_input, result);

And you should use %d as you are printing integers..

%3d will be replaced by numberLoop.

%4d will be replaced by num_input

%5d will be replaced by result

And you will get the output like: -

numberLoop(3 spaces) * num_input(4 spaces) = result(5 spaces)

%3d is for right justification.. and %-3d is for left justification.. You can use either of them..

You can also store your formatted string into a String variable by using String.format(), and you can later print that string variable: -

String result = String.format("%3d * %4d = %5d\n", numberLoop, num_input, result)

NOTE: - For more formatting options, you can go through documentation of Formatter class..

Upvotes: 4

Related Questions