aaaa
aaaa

Reputation: 21

multiplication table formatting issue

Currently when I run my code it displays the basic multiplication vertically.

1
2
2
4

How would I get it to display in table format like horizontally and vertically to form a table? Assuming that i and j are how big you want the table to be.

123
246
369

Code

for(int i=1; i<=2; i++){
    for (int j=1; j <= 2; j++){
        //int multiplier =1;
        int answer = i*j;
        //multiplier++;  
        System.out.println(answer);
    }
}

Upvotes: 0

Views: 44

Answers (1)

user5182794
user5182794

Reputation:

For a simpler method, you can use 'System.out.print()' (only works for same length results):

for(int i=1; i<=2; i++){
    for (int j=1; j <= 2; j++){
        //int multiplier =1;
        int answer = i*j;
        //multiplier++;  
        System.out.print(answer+" ");
    }
    System.out.println();
}

Otherwise, you can use 'System.out.format()':

for(int i=1; i<=10; i++){
    for (int j=1; j <= 10; j++){
        //int multiplier =1;
        int answer = i*j;
        //multiplier++;  
        System.out.format("%5s", answer);
    }
    System.out.println();
}

More information about 'System.out.format()': https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

Upvotes: 2

Related Questions