在java中打印如下的特定数字模式

时间:2018-03-13 10:55:22

标签: java

我是java编程的新手,并试图实现以下数字模式打印。 它是基于从用户接收的输入的方阵,矩阵将如下所示;(前n行中的前n个数字和最下行的n个数字,现在再次接下来n个数字在第2行和下n个数字在最后但一行等等......)

If n=3;
1 2 3
7 8 9
4 5 6

If n=4;
1 2 3 4
9 10 11 12
13 14 15 16 
5 6 7 8

虽然我觉得一切正常,但执行过程中出错 - java.lang.ArrayIndexOutOfBoundsException:抛出。你能告诉我吗?

import java.util.*;

class TopBottomNumbers {
    public static void main(String[] args) {
        int s = 1, n;
        int a[][];
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the number of rows to print the pattern: ");
        n = sc.nextInt();

        a = new int[n - 1][n - 1];

        for (int i = 0; i < (n / 2); i++) {
            for (int j = 0; j < n; j++) {
                a[i][j] = s;
                a[n - 1][j] = s + n;
                s++;
            }

            s = s + n;
        }

        if (n % 2 != 0) {
            for (int i = 0; i < n; i++) {
                a[n / 2][i] = s;
                s++;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

正如人们在评论中指出的那样,错误是由这一行引起的:

a = new int[n - 1][n - 1];

这意味着如果用户引入数字4,你将得到一个3(0,1,2)的角度,选择你想要的4(0,1,2,3)。

如果删除-1