題目:
根據輸入的n,打印n行乘法口訣表。
需要使用二維字符串數組存儲乘法口訣表的每一項,比如存放1*1=1
.
為了保證程序中使用了二維數組,需在打印完乘法口訣表后使用Arrays.deepToString
打印二維數組中的內容。
提醒:格式化輸出可使用String.format
或者System.out.printf
。
輸出格式說明
- 每行末尾無空格。
- 每一項表達式之間(從第1個表達式的第1個字符算起到下一個表達式的首字符之間),共有包含7個字符。如
2*1=2 2*2=4
從第1個2開始到第二項`2*2=4
首字母之間,總共有7個字符(包含空格,此例中包含2個空格)。
輸入樣例:
2
5
輸出樣例:
1*1=1
2*1=2 2*2=4
[[1*1=1], [2*1=2, 2*2=4]]
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
[[1*1=1], [2*1=2, 2*2=4], [3*1=3, 3*2=6, 3*3=9], [4*1=4, 4*2=8, 4*3=12, 4*4=16], [5*1=5, 5*2=10, 5*3=15, 5*4=20, 5*5=25]]
代碼:
1 import java.util.Scanner; 2 import java.util.Arrays; 3 public class Main { 4 public static void main(String[] args) { 5 Scanner sc = new Scanner(System.in); 6 while(sc.hasNextInt()) { 7 int n = sc.nextInt(); 8 String[][] arr = new String[n][]; 9 for(int i = 0;i < n;i++) { 10 arr[i] = new String[i+1]; 11 for(int j = 0;j < i+1;j++) { 12 arr[i][j] = (i+1)+"*"+(j+1)+"="+(i+1)*(j+1); 13 if(j<i) 14 System.out.printf("%-7s",arr[i][j]); 15 else if(j==i) 16 System.out.printf("%s",arr[i][j]); 17 } 18 System.out.println(); 29 } 20 System.out.println(Arrays.deepToString(arr)); 21 } 22 } 23 }
筆記:
1.格式限定每個表達式之間包含7個字符,因此想到了格式化輸出,用“%-7s”控制字符串占七個字符位,負號表示左對齊
int [][] arr ;
2.動態創建二維數組:
arr = new int [ 一維數 ][]; //動態創建第一維
for ( i = 0 ; i < 一維數 ; i++ ) {
arr [ i ] = new int [ 二維數 ]; //動態創建第二維
for( j=0 ; j < 二維數 ; j++) {
arr [i][j] = j;
}
}