Reputation: 41
I am practicing for loops and for one of the end-of-the-chapter exercises, it is asking to create a multiplication table that show the results multiplying the integers from 1 to 12 by themselves. This is what I did, which produces a wrong result. I am sure I am missing something simple but can't catch it.
public class PP63 {
public static void main(String[] args) {
final int TOTAL = 12;
for(int i = 1; i <= TOTAL; i++)
{
for(int j = 1; j<=TOTAL; j++)
{
System.out.println(i*j);
}
}
}
}
Upvotes: 0
Views: 3378
Reputation: 3182
use this code inside your main method. I hope you would like it
final int TOTAL = 12;
for(int i = 1; i <= TOTAL; i++)
{
for(int j = 1; j<=TOTAL; j++)
{
if(i*j<10)
System.out.print(j+"*"+i+" = "+i*j +" ");
else if(10<=i*j & i*j<100)
System.out.print(j+"*"+i+" = "+i*j +" ");
else if(100<=i*j & i*j<1000)
System.out.print(j+"*"+i+" = "+i*j +" ");
}
System.out.println("");
}
Upvotes: 0
Reputation: 1568
According to you problem i think you are getting all the result mixed in one line so you should do it like this way :
public class PP63
{
public static void main (String[] args) {
// print main table
for (int i = 1; i <= 12; i++) {
System.out.print(i + ":");
for (int j = 1; j <= 12; j++) {
System.out.print(i*j + " ");
}
System.out.println();
}
} // end of main
}
Upvotes: 0
Reputation: 27792
Basically, you want a table, not a list
for(int i = 1; i <= TOTAL; i++)
{
for(int j = 1; j<=TOTAL; j++)
{
System.out.print(i*j + "\t");
}
System.out.println();
}
Upvotes: 2
Reputation: 372814
One issue here is this line:
System.out.println(i*j);
Notice that this is calling println
, which prints the value on its own line. If you want to print multiple values on the same line, you can use System.out.print
instead. You'll need to manually insert whitespace to make sure everything aligns properly and will have to insert your own newlines as well.
Hope this helps!
Upvotes: 1