我需要制作一个从1 * 1到12 * 12的乘法表。我有这个工作,但它需要在13列的格式,看起来像下面的图表,真的很感谢任何帮助。
1 2 3 4 5 6 7 8 9 10 11 12
1 1 2 3 4 5 ...
2 2 4 6 8 10 ....
3
4
5
6
...
目前代码:
public class timetable {
public static void main(String[] args) {
int[][] table = new int[12][12];
for (int row=0; row<12; row++){
for (int col=0; col<12; col++){
table[row][col] = (row+1) * (col+1);
}
}
for (int row = 0; row < table.length; row++) {
for (int col = 0; col < table[row].length; col++) {
System.out.printf("%6d", table[row][col]);
}
System.out.println();
}
}
}
在打印表格之前打印列标题,并在每行开头打印行标题。您可以使用下面的代码:
int[][] table = new int[12][12];
for (int row=0; row<12; row++){
for (int col=0; col<12; col++){
table[row][col] = (row+1) * (col+1);
}
}
// Print column headings
System.out.printf("%6s", "");
for (int col = 0; col < table[0].length; col++) {
System.out.printf("%6d", col+1);
}
System.out.println();
for (int row = 0; row < table.length; row++) {
// Print row headings
System.out.printf("%6d", row+1);
for (int col = 0; col < table[row].length; col++) {
System.out.printf("%6d", table[row][col]);
}
System.out.println();
}
这只打印9x9时间表,如果您需要将其更改为12x12,则只需将代码中的数字从"9"更改为"12",并在系统输出中添加更多"----"行以匹配它
这包括" * |"one_answers"----"…我想这可能对其他人有帮助
输出:9 x9时间表
public class timetable2DArray
{
public static void main(String[] args)
{
int[][] table = new int[9][9];
for (int row=0; row<9; row++)
{
for (int col=0; col<9; col++)
{
table[row][col] = (row+1) * (col+1);
}
}
// Print column headings
System.out.print(" * |");
for (int col = 0; col < table[0].length; col++)
{
System.out.printf("%4d", col+1);
}
System.out.println("");
System.out.println("------------------------------------------");
for (int row = 0; row < table.length; row++)
{
// Print row headings
System.out.printf("%4d |", row+1);
for (int col = 0; col < table[row].length; col++)
{
System.out.printf("%4d", table[row][col]);
}
System.out.println();
}
}
}
int [][] A = new int[5][5];
int [][] B = new int[5][5];
for (int row = 0; row < A.length; row++) {
System.out.println();
for (int col = 0; col < A.length; col++) {
B[row][col] = (row+1)*(col+1);
System.out.print("t");
System.out.printf("%2d", B[row][col]);
}
}
您可以实现一个timesTable()方法。这是我的代码,你可以随意修改。
//main driver
public static void main(String[] args) {
int[][] data; //declaration
data = timesTable(4,6); //initialisation
for (int row = 0; row < data.length ; row++)
{
for (int column = 0; column < data[row].length; column++)
{
System.out.printf("%2d ",data[row][column]);
}
System.out.println();
}
}
//method
public static int[][] timesTable(int r, int c)
{
int [][] arr = new int[r][c];
for (int row = 0; row < arr.length ; row++)
{
for (int column = 0; column < arr[row].length; column++)
{
arr[row][column] = (row+1)*(column+1);
}
}
return arr;
}