jsbdjx 2023-11-14 18:31 采纳率: 100%
浏览 4
已结题

JAVA代码报错java.lang.NullPointerException

请问为什么会报错Exception in thread "main" java.lang.NullPointerException?

对java类的定义还不是太熟练,请告诉我这段代码暴露出我的规范性问题,这段代码定义了一个接口,之后定义了一个类实现这个接口,最后主函数调用类进行计算

代码如下

import java.util.*;

public interface Exponentiation<T> {

    T Muti(T multiplier1, T multiplier2); // 定义乘法

    void Unitary(); // 定义幺元

    T FastPower_Curculate(T base, Integer index); // 循环快速幂

}

class Matrix_base implements Exponentiation<Integer[][]> {
    Integer[][] unitary;
    Integer side;
    

    public void Set_Side(Integer Side){
        side= Side;
    }

    public Integer[][] Muti(Integer[][] multiplier1, Integer[][] multiplier2) {
        Integer[][] answer=  new Integer[side][side];
        for (int i = 0; i < side; i++) {
            for (int j = 0; j < side; j++) {
                answer[i][j]= 0;
                for (int k = 0; k < side; k++) {
                    answer[i][j] += multiplier1[i][k] * multiplier2[k][j];
                }
            }
        }
        return answer;
    }

    public void Unitary() {
        unitary = new Integer[side][side];
        for (int i = 0; i < side; i++) {
            unitary[i][i] = 1;
        }
    }

    public Integer[][] FastPower_Curculate(Integer[][] base, Integer index) {
        Integer[][] result = unitary;
        while (index > 0) {
            if ((index & 1) == 1) {
                result = Muti(result, base);
            }
            base = Muti(base, base);
            index >>= 1;
        }
        return result;
    }
}

class Result {
    public static void main(String[] args) {
        Matrix_base yunsuan = new Matrix_base();
        yunsuan.Set_Side(3);
        Integer[][] base = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        Integer[][] ans = yunsuan.FastPower_Curculate(base, 2);
        System.out.println(Arrays.deepToString(ans));
    }

}

报错如下

Exception in thread "main" java.lang.NullPointerException
        at Matrix_base.Muti(Exponentiation.java:28)
        at Matrix_base.FastPower_Curculate(Exponentiation.java:46)
        at Result.main(Exponentiation.java:60)
  • 写回答

2条回答 默认 最新

  • jsbdjx 2023-11-14 19:30
    关注

    哈哈,终于给我想出来了,初始化幺元矩阵只赋值了1,其他全是null,怪不得全会空指针,啊哈哈哈哈哈哈哈

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 11月22日
  • 已采纳回答 11月14日
  • 创建了问题 11月14日