JAVA矩阵程序仅打印0秒而不接受输入

Luk*_*igh 2 java arrays matrix

我的程序运行没有错误.但是,以某种方式跳过readInput方法.这导致仅打印0.

另外,如何修改我的displayResult方法,以使我的输出在显示中更像"矩阵状".

我的源代码如下.

import java.util.Scanner;
public class Matrices {
    int i, j, k, n = 3;
    int[][] matA = new int[n][n];
    int[][] matB = new int[n][n];
    int[][] matSum = new int[n][n];
    int[][] matProd = new int[n][n];

    public void readInput() {
        Scanner scan = new Scanner(System.in);
        for (i = 0; n < 3; i++) {
            for (j = 0; j < n; j++) {
                System.out.println("matA[" + i + "][" + j + "]");
                matA[i][j] = scan.nextInt();
                System.out.println("matA[" + i + "][" + j + "]");
                matA[i][j] = scan.nextInt();
            }
        }
    }

    public void findSum() {
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                matSum[i][j] = matA[i][j] + matB[i][j];
            }
        }
    }

    public void findProduct() {
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                for (k = 0; k < n; k++) {
                    matProd[i][j] = matProd[i][j] + matA[i][j] * matB[i][j];
                }
            }
        }
    }

    public void displayResult() {
        // Printing the Sum Matrix
        System.out.println("Sum Matrix is:");
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                System.out.println(matSum[i][j] + " ");
            }
        }

        // Printing the Product Matrix
        System.out.println("Product Matrix is:");
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                System.out.println(matProd[i][j] + " ");
            }
        }
        System.out.println();
    }

public static void main(String[] args){

    System.out.println("Matrix Calculator");
    System.out.println("-------------------\n");
    Matrices self = new Matrices();

    self.readInput();
    self.findSum();
    self.findProduct();
    self.displayResult();
}
}
Run Code Online (Sandbox Code Playgroud)

ΦXo*_*a ツ 5

您的读取输入方法因此无效:

 for (i = 0; n < 3; i++) {
Run Code Online (Sandbox Code Playgroud)

因为n被声明并且init被初始化为3,所以条件n <3返回false,所以矩阵永远不会被填充,之后的所有内容都是基于零矩阵的jsut!