Trying to figure out how to print a multiplication table. The code I have right now is:
Scanner scan= new Scanner(System.in);
System.out.print("Please enter number 1-10:");
int n=scan.nextInt();
if(n<=10)
{
for(int m= 1;m<=n;m )
{
for(int o= 1;o<=n;o )
{
System.out.print(m*o "\t");
}
System.out.println();
}
}
else
System.out.print("INVALID");
It prints out :
I'm trying to get it to print out as :
CodePudding user response:
Please read the comments marked with // CHANGE HERE
.
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter number 1-10: ");
int n = scan.nextInt();
// CHANGE HERE - strict checking
if (n >= 1 && n <= 10)
{
// CHANGE HERE - added to print the first (header) row
for (int m = 0; m <= n; m )
{
if (m == 0)
System.out.print("\t");
else
System.out.print(m "\t");
}
System.out.println();
for (int m = 1; m <= n; m )
{
// CHANGE HERE - added to print the first column
System.out.print(m "\t");
for (int o = 1; o <= n; o )
{
System.out.print(m * o "\t");
}
System.out.println();
}
}
else
System.out.println("INVALID");
}
}
CodePudding user response:
Try this.
Scanner scan = new Scanner(System.in);
System.out.print("Please enter number 1-10:");
int n = scan.nextInt();
if (n <= 10) {
for (int i = 1; i <= n; i)
System.out.print("\t" i);
System.out.println();
for (int m = 1; m <= n; m ) {
System.out.print(m);
for (int o = 1; o <= n; o ) {
System.out.print("\t" m * o);
}
System.out.println();
}
} else
System.out.print("INVALID");
output:
Please enter number 1-10:7
1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 4 6 8 10 12 14
3 3 6 9 12 15 18 21
4 4 8 12 16 20 24 28
5 5 10 15 20 25 30 35
6 6 12 18 24 30 36 42
7 7 14 21 28 35 42 49