Sinicaphak 2022-07-18 20:37 采纳率: 50%
浏览 28
已结题

等号两边调换导致空指针异常

问题遇到的现象和发生背景

0基础自学java中,在学习对象的创建与应用时遇到该问题.
代码中的引用类型: Student,Pc

问题相关代码,请勿粘贴截图

public class A {
public static void main(String[] args) {
    
    //实例化一个 "学生A"
    Student studentA = new Student();
    
    //实例化ac,指向学生A的电脑
    Pc ac =new Pc();
    ac = studentA.computer;

    //为学生A的电脑的型号赋值
    studentA.computer.model="asdf";
    
    //ac指向studentA.computer.brand,并赋值
    ac.brand = "HP";
    //ac指向studentA.computer.color,并赋值
    ac.color = "white";
    
    //输出结果
    System.out.println(studentA.name ="qwe");
    System.out.println(studentA.code = 114514);
    System.out.println("A学生电脑的品牌为" + ac.brand);
    System.out.println("A学生电脑的型号为" + studentA.computer.model);
    System.out.println("A学生电脑的颜色为" + studentA.computer.color);
    
}
}


运行结果及报错内容

空指针报错

报错内容:
Exception in thread "main" java.lang.NullPointerException: Cannot assign field "model" because "studentA.computer" is null
at A.main(A.java:12)

我的解答思路和尝试过的方法

实例化ac时将

ac = studentA.computer;    

替换为

studentA.computer = ac;

运行正常

我想要达到的结果

我想明白:为什么只是等号两遍的引用调换位置就会发生空指针异常?

  • 写回答

4条回答 默认 最新

  • it_hao528 2022-07-18 22:50
    关注

    1、ac = studentA.computer;是将studentA.computer赋值给ac,而studentA.computer在创建studentA的时候并没有实例化是空的,所以在调用studentA.computer.model="asdf";时会报空指针异常,也就是说只要studentA.computer是空的,那么只要调用其属性或者方法都会报空指针异常,因为程序不能找到是谁调的。
    2、studentA.computer = ac;是将ac赋值给studentA.computer,ac是new出来的一个新对象,其不是空的,所以将ac赋值给studentA.computer之后,studentA.computer也不是空的,此时调用其属性和方法是正常的,也就不会报错了。

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

报告相同问题?

问题事件

  • 系统已结题 8月17日
  • 已采纳回答 8月9日
  • 创建了问题 7月18日

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。