jmu-Java-02基本语法-04-动态数组
2020-12-13 16:44
标签:动态创建 str 内容 程序 string static 格式化 控制 tor 题目: 根据输入的n,打印n行乘法口诀表。 提醒:格式化输出可使用
需要使用二维字符串数组存储乘法口诀表的每一项,比如存放1*1=1
.
为了保证程序中使用了二维数组,需在打印完乘法口诀表后使用Arrays.deepToString
打印二维数组中的内容。String.format
或者System.out.printf
。输出格式说明
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 ) {
10 arr[i] = new String[i+1];
11 for(int j = 0;j ) {
12 arr[i][j] = (i+1)+"*"+(j+1)+"="+(i+1)*(j+1);
13 if(ji)
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 }
笔记:
arr [ i ] = new int [ 二维数 ]; //动态创建第二维1.格式限定每个表达式之间包含7个字符,因此想到了格式化输出,用“%-7s”控制字符串占七个字符位,负号表示左对齐
int [][] arr ;
2.动态创建二维数组:
arr = new int [ 一维数 ][]; //动态创建第一维
for ( i = 0 ; i ; i++ ) {
for( j=0 ; j ; j++) {
arr [i][j] = j;
}
}
jmu-Java-02基本语法-04-动态数组
标签:动态创建 str 内容 程序 string static 格式化 控制 tor
原文地址:https://www.cnblogs.com/dotime/p/11621516.html