m0_74004453 2022-10-22 17:26 采纳率: 80%
浏览 16
已结题

关于方法传参里数组对象作为参数的疑问

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

目前在学习带参方法的传参,其中遇到了一个问题,如果参数为某个对象数组时,遇到的报错

用代码块功能插入代码,请勿粘贴截图

Student类:
public class Student {
String name;
int age;

public void show() {
    System.out.println("姓名为:"+name+"年龄:"+age);
}

}

TestStu测试类:
public class TestStu {
public static void main(String[] args) {
Student stu = new Student();

    //创建一个Student类型的数组,里面存放stu1 这个对象
    Student [] stu1 = new Student[3];
    //数组初始化
    stu1[0].age=12;
    stu1[0].name="王强";
    stu1[1].age=15;
    stu1[1].name="刘备";
    stu1[2].age=11;
    stu1[2].name="祖师爷";
    
    //用Student类里的show方法打印这个数组
    for (int i = 0; i < stu1.length; i++) {
        stu1[i].show();
    }        
}

}

运行结果及报错内容

报错提示:
Exception in thread "main" java.lang.NullPointerException
at fuxi.TestStu.main(TestStu.java:9)

我想要达到的结果

请问这个为什么会报错呢?

  • 写回答

1条回答 默认 最新

  • 梦里逆天 2022-10-22 17:35
    关注

    对象都没有创建

    class Student {
        String name;
        int age;
    
        public void show() {
            System.out.println("姓名为:"+name+"年龄:"+age);
        }
    }
    
    public class TestStu {
        public static void main(String[] args) {
    
            //创建一个Student类型的数组,里面存放stu1 这个对象
            Student [] stu1 = new Student[3];
            stu1[0] = new Student();
            stu1[1] = new Student();
            stu1[2] = new Student();
            //数组初始化
            stu1[0].age=12;
            stu1[0].name="王强";
            stu1[1].age=15;
            stu1[1].name="刘备";
            stu1[2].age=11;
            stu1[2].name="祖师爷";
    
            //用Student类里的show方法打印这个数组
            for (int i = 0; i < stu1.length; i++) {
                stu1[i].show();
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

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

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法