gpt4 book ai didi

java - 主线程异常。不知道原因

转载 作者:行者123 更新时间:2023-12-01 11:21:28 25 4
gpt4 key购买 nike

package examples;
import java.util.Scanner;

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

以下 4 部分标识两个矩阵的行和列的用户输入。

        Scanner userrows1 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 1: ");
int rows1 = userrows1.nextInt();

Scanner usercolumns1 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns1 = usercolumns1.nextInt();

Scanner userrows2 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 2: ");
int rows2 = userrows2.nextInt();

Scanner usercolumns2 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns2 = usercolumns2.nextInt();

这将对象matrix1和matrix2设置为属于Matrix类

        Matrix matrix1 = new Matrix(rows1, columns1);
Matrix matrix2 = new Matrix(rows2, columns2);

matrix1.ShowMatrix();
System.out.println("\n \n");

matrix2.ShowMatrix();

}

}


class Matrix {

int rows;
int columns;
int[][] values;

public Matrix(int r, int c) {
rows = r;
columns = c;

int[][] values = new int[r][c];

这最初是为了允许用户逐一输入矩阵的值。为了简单起见,现在我只是将矩阵的所有值设置为某个值。

        int i;
int j;
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
//Scanner userelement = new Scanner(System.in);
//System.out.println("Enter number:");
//int element = userelement.nextInt();
values[i][j] = 1;

}


}



}


public void ShowMatrix() {
int k;
int l;
for(k = 0; k < rows; k++) {
for(l = 0; l < columns; l++) {
System.out.println(values[k][l] + " ");

}
System.out.println("\n");

}


}


}


The code is above. In the final method in the class Matrix (the method is ShowMatrix), I am trying to print out the matrix. However, I am using the general values matrix here and it says:

Exception in thread "main" java.lang.NullPointerException
at examples.Matrix.ShowMatrix(MatrixMultiplication.java:75)
at examples.MatrixMultiplication.main(MatrixMultiplication.java:29)

Can anyone diagnose the issue? Much thanks as I'm still very new to Java.

最佳答案

您尚未实例化字段[][]values(存在int[][]值的本地声明)。

public Matrix(int r, int c) {
rows = r;
columns = c;

int[][] values = new int[r][c]; <-- Remove this
values = new int[r][c];
....
}

关于java - 主线程异常。不知道原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31175336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com