2013-07-23 25 views
-4

程序如何根據用戶輸入的大小顯示乘法表?並會添加每一行和每一列?事情是這樣的:Java乘法

Enter a number: 4 
1 2 3 4 10 
2 4 6 8 20 
3 6 9 12 30 
4 8 12 16 40 
10 20 30 40 

我嘗試這樣做:

Scanner s = new Scanner(System.in); 
System.out.print("Enter a number: "); 
int x = s.nextInt(); 
for(int i = 1; i <= x; i++) 
{ 
    for (int j = 1; j <=x; j++) 
    { 
     System.out.print((i*j) + "\t"); 
    } 
    System.out.println(); 
} 

樣本輸出:

Enter a number: 4 
1 2 3 4 
2 4 6 8 
3 6 9 12 
4 8 12 16 

我怎麼會做補充每一行和每一列?

+1

我會推薦使用數組 –

+2

如果它總是一個正方形,每一行/ col上的數字將是相同的。所以當你繪製每一行時,可能只是保留一個總數(也許是一個數組)。然後,在最後一行,只需繪製出你建立的數組。 –

回答

1
public static void main(String[] args){ 
Scanner s = new Scanner(System.in); 
System.out.print("Enter size of table: "); 
int x = s.nextInt(); 
int r = 0; 
int l = 0; 
int f = 0; 
for(int i=1;i<=x;i++){  
    for (int j=1; j <=x; j++) 
    { 
     r = r + j; 
     System.out.print(i*j+"\t"); 
    } 
    System.out.print(r); 
    System.out.println(); 
    System.out.println(); 
    l=l+i; 
} 
for(int k = 1; k<=x;k++) 
{ 
f=f+l; 
System.out.print(f + "\t"); 
} 
1

由於這看起來像是功課,所以我不願意爲你寫代碼。但是,請記住以下事項。

  1. 你的矩陣將始終是一個正方形,當用戶只輸入一個單個數字,n X n數字。
  2. 由於這些數字沿着行和列增加1,因此每個行和列對的總和將相同。換句話說,總共行[n]將等於列的總和[n]

使用它,您可以創建一個大小爲n的單個數組來存儲每行的總和。例如:

Enter a number: 3 
1 2 3 x 
2 4 6 y 
3 6 9 z 
x y z 

當您遍歷每一行時,您可以將行總數存儲在數組中。

Row 0: Add 1 + 2 + 3 and store in array[0] 
Row 1: Add 2 + 4 + 6 and store in array[1] 
Row 2: Add 3 + 6 + 9 and store in array[2] 

截至每一行你可以簡單地在array[row]顯示總的結束。當您完成繪製所有行時,您只需循環顯示array並顯示每個總值。

希望這點能指引您朝着正確的方向發展!