jmu-Java-02基本语法-04-动态数组

题目:

根据输入的n,打印n行乘法口诀表。
需要使用二维字符串数组存储乘法口诀表的每一项,比如存放1*1=1.
为了保证程序中使用了二维数组,需在打印完乘法口诀表后使用Arrays.deepToString打印二维数组中的内容。

提醒:格式化输出可使用String.format或者System.out.printf

输出格式说明

  1. 每行末尾无空格。
  2. 每一项表达式之间(从第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”控制字符串占七个字符位,负号表示左对齐
2.动态创建二维数组:
  
  int [][] arr ;
     arr = new int [ 一维数 ][]; //动态创建第一维
     for ( i = 0 ; i < 一维数 ; i++ ) {
      arr [ i ] = new int [ 二维数 ]; //动态创建第二维
       for( j=0 ; j < 二维数 ; j++) {
         arr [i][j] = j;
       }
     }
 

猜你喜欢

转载自www.cnblogs.com/dotime/p/11621516.html