n-by-n整数数组

时间:2016-05-06 19:09:19

标签: java matrix calc

问题陈述:

我想编写一个从标准输入中读取正整数n的程序,并创建一个n乘n整数数组a[][],使得a[i][j]是(i + 1)的乘积第(j + 1)列的第n行。

当前代码:

Scanner input = new Scanner(System.in);
String inputString;
char flag = 'y';
while (flag != 'q' && flag != 'Q') {
    System.out.print("Enter a positive integer:");
    int value = input.nextInt();
    System.out.printf("Enter q to quit or any other key to quit: ");
    input.nextLine();
    inputString = input.nextLine();
    flag = inputString.charAt(0);
}

例如

如果用户输入3,则矩阵需要为3x3并且乘以1的乘积乘以1乘以2乘以1然后乘以3.然后对2和3执行相同的操作。

2 个答案:

答案 0 :(得分:1)

您的问题的算法描述应如下所示:

步骤1:用户输入正整数n
第2步:创建一个n x n矩阵
步骤3:对于每个元素(i,j),(i,j)处矩阵的值为(i + 1)*(j + 1)

实施:

public class Snippet {
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.print("Enter a positive integer:");
    int n = input.nextInt();

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

    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a.length; j++) {
            a[i][j] = (i + 1) * (j + 1);
        }
    }

    for (int[] is : a) {
        System.out.println(Arrays.toString(is));
    }
 }
}

答案 1 :(得分:-3)

 public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    String inputString;
    char flag = 'y';
    int matrix[][];
    while (flag != 'q' && flag != 'Q') {
        System.out.print("Enter a positive integer:");
        int value = input.nextInt();
        System.out.printf("Enter q to quit or any other key to quit: ");
        if(value > 0){
            matrix = new int[value][value];
            displayOutput(matrix);
        }

        input.nextLine();
        inputString = input.nextLine();
        flag = inputString.charAt(0);
    }
}

private static void displayOutput(int[][] matrix) {
    for (int i = 0; i < matrix.length; i++) {

        matrix[i][0] = i+1;
    }
    for (int j = 1; j < matrix.length; j++) {
        for (int i = 0; i < matrix.length; i++) {
            matrix[i][j] = matrix[i][0]*(j+1);
        }            
    }

    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix.length; j++) {
            System.out.print(" "+matrix[i][j]);
        }
        System.out.println("");
    }

}
Input: 3
Outputs: 1 2 3
         2 4 6
         3 6 9