1.Java 创建自定义类数组方法:
นักเรียน [] stu = นักเรียนใหม่ [3]; สำหรับ (int i = 0; i <3; i ++) {stu [i] = นักเรียนใหม่ ();2. 否则会提示空指针异常
โครงการแพ็คเกจ; นำเข้า java.io.*; นำเข้า java.util.scanner; นักเรียนชั้นเรียน {ID ส่วนตัว int; ชื่อสตริงส่วนตัว; คะแนน INT ส่วนตัว; โมฆะสาธารณะ setId (int id) {this.id = id; } public int getId () {return this.id; } โมฆะสาธารณะ setName (ชื่อสตริง) {this.name = name; } สตริงสาธารณะ getName () {return this.name; } โมฆะสาธารณะ setScore (คะแนน int) {this.score = คะแนน; } public int getScore () {return this.score; }} คลาสสาธารณะ Project2 {ไฟล์ไฟล์ = ไฟล์ใหม่ ("e: /data.txt"); fileWriter fileWrite = null; bufferedWriter write = null; filereader fileread = null; bufferedReader read = null; นักเรียน [] stu = นักเรียนใหม่ [3]; โมฆะสาธารณะ Put () {ลอง {fileWrite = ใหม่ fileWriter (ไฟล์); } catch (ioexception e) {// todo 自动生成的จับ块 E.printstacktrace (); } เขียน = ใหม่ bufferedWriter (fileWrite); สำหรับ (int i = 0; i <3; i ++) {system.out.println ("请输入第" + (i + 1) + "个学生的 id, 姓名, 成绩:"); สแกนเนอร์ใน = สแกนเนอร์ใหม่ (System.in); ลอง {string str = in.nextline (); ข้อมูลสตริง [] = str.split (""); สำหรับ (int j = 0; j <3; j ++) {write.write (data [j]); write.newline (); }} catch (ioexception e) {// todo 自动生成的จับ块 E.printstackTrace (); }} ลอง {write.close (); fileWrite.close (); } catch (ioexception e) {// todo 自动生成的จับ块 E.printstacktrace (); }} โมฆะสาธารณะ get () {int sum = 0; Ave สองครั้ง; ลอง {fileread = new filereader (ไฟล์); } catch (filenotfoundexception e) {// todo 自动生成的จับ块 E.printstacktrace (); } read = ใหม่ bufferedReader (fileread); สำหรับ (int i = 0; i <3; i ++) {stu [i] = นักเรียนใหม่ (); ลอง {stu [i] .setId (integer.parseint (read.readline ())); stu [i] .setName (read.readline ()); stu [i] .setscore (integer.parseint (read.readline ())); } catch (exception e) {// todo 自动生成的 catch 块 e.printstacktrace (); }} สำหรับ (int i = 0; i <3; i ++) {sum += stu [i] .getScore (); } ave = sum * 1.0/3; System.out.println ("学生的平均成绩为:" + ave); ลอง {read.close (); fileread.close (); } catch (ioexception e) {// todo 自动生成的จับ块 E.printstacktrace (); }} โมฆะคงที่สาธารณะหลัก (สตริง [] args) {project2 pro = ใหม่ Project2 (); pro.put (); pro.get (); -总结:
这样我们就可以在项目当中, 根据项目需求自己来定义想要的数组