2013-08-29 40 views
-2

我想用简单的循环和数组创建一个简单的java程序。它应该是乘法表。java中的简单乘法数组

如果行数是3,列数是5,那么它应该显示行,列,并在矩阵内应该给行和列的乘法。输出应该看起来像这样。

 1 2 3 4 5 
1 1 2 3 4 5 
2 2 4 6 8 10 
3 3 6 9 12 15 

这个我想创建简单的循环。我是新来的Java,所以我无法弄清楚我该如何做到这一点。请让我知道。

我已经完成了代码,直到这里。

import java.util。*;

class cross_multiplication 
{ 

    public static void main(String a[]) 
     { 

     System.out.println("How many rows required? : "); 
     Scanner in1 = new Scanner(System.in); 
     int num_rows = in1.nextInt(); 

     System.out.println("How many cols required? : "); 
     Scanner in2 = new Scanner(System.in); 
     int num_cols = in2.nextInt(); 

    //int arr1 [] = new int[num_rows]; 
    //int arr2 [] = new int[num_cols];  

     for(int i=0;i<num_rows;i++) 
     { 
       if (i==0) 
       { 
        System.out.print(""); 
       } 
       else 
       { 
        System.out.print(i);    
       } 
       System.out.print("\t");  

     } 


    } 
} 

感谢

+3

使用数组和循环然后问你以后试过 –

+1

你有没有试过任何代码? – sanbhat

+1

不知道为什么你会需要一个数组,但一个简单的复合'for-loop'应该这样做。 – MadProgrammer

回答

1

要包括标题,你需要检查你是否在列0(j == 0)或列0(i == 0)。如何做到这一点的示例:

public static void print(int x, int y) { 
    for (int i = 0; i <= x; i++) { 
    for (int j = 0; j <= y; j++) { 
     if(i==0) { // first row 
     if(j>0) { 
      System.out.printf("%d\t", j); 
     } 
     else { // first row, first column: blank space 
      System.out.printf("\t"); 
     } 
     } 
     else { 
     if(j == 0) { // first column 
      System.out.printf("%d\t", i); 
     } 
     else { // actually in the body of the table - finally! 
      System.out.printf("%d\t" i * j); 
     } 
     } 
    } 
    System.out.println(); 
    } 
} 
3

你可以尝试这样的事:

private static void print(final int[][] table){ 
    for(int r = 0; r < table.length; r++){ 
     for(int c = 0; c < table[r].length; c++){ 
      System.out.printf("%d\t", table[r][c]); 
     } 
     System.out.println(); 
    } 
} 

private static int[][] table(final int rows, final int columns){ 
    final int[][] array = new int[rows][columns]; 
    for(int r = 1; r <= rows; r++) 
     for(int c = 1; c <= columns; c++) 
      array[r-1][c-1] = r * c; 
    return array; 
} 

从上面的代码,如果你要打印10×10乘法表,你可以这样做:

print(table(10, 10)); 

输出结果如下:

10x10 output

+0

现在我们只需将标题重新添加到... – Floris

+0

@弗洛里斯当然,OP将能够自己添加标题。 –

+0

我没有说你必须为他做。因此,“我们必须添加”,而不是“嘿乔希,你忘了标题”。边干边学... – Floris

1

IM不会给你答案,但我会给你一些伪

你没有正确设置了2个循环

Loop x = 1 to 3 
    Loop y = 1 to 3 
     //Do stuff 
    End innerloop 
End outerloop 

这将打印所有的解决方案在一条直线, 单线。但是你希望它明显在矩阵中。答案是简单的一个简单的改变,只需要一行代码。在你内循环的每个完整周期之后,你基本上完成了一行乘法(想一想为什么)。所以解决方法是,在内循环结束运行之后,在转到x的下一个外循环值之前,您想要打印一个新行。总之,我们有这样的事:

Loop x = 1 to 3 
    Loop y = 1 to 3 
     z = x * y 
     Print z + " " 
    End innerloop 
    Print NewLine // "\n" is the way to do that 
End outerloop 

,并尝试

public static void print(int x, int y) { 
    for (int i = 1; i <= x; i++) { 

     for (int j = 1; j <= y; j++) { 

      System.out.print(" " + i * j); 
     } 
     System.out.println(); 

    } 
}