java 创建自定义数组
1.java创建自定义类数组方法:
Student[]stu=newStudent[3]; for(inti=0;i<3;i++) { stu[i]=newStudent(); }
2.否则会提示空指针异常
packageproject; importjava.io.*; importjava.util.Scanner; classStudent { privateintid; privateStringname; privateintscore; publicvoidsetId(intid) { this.id=id; } publicintgetId() { returnthis.id; } publicvoidsetName(Stringname) { this.name=name; } publicStringgetName() { returnthis.name; } publicvoidsetScore(intscore) { this.score=score; } publicintgetScore() { returnthis.score; } } publicclassproject2{ Filefile=newFile("E:/data.txt"); FileWriterfilewrite=null; BufferedWriterwrite=null; FileReaderfileread=null; BufferedReaderread=null; Student[]stu=newStudent[3]; publicvoidput() { try{ filewrite=newFileWriter(file); }catch(IOExceptione){ //TODO自动生成的catch块 e.printStackTrace(); } write=newBufferedWriter(filewrite); for(inti=0;i<3;i++) { System.out.println("请输入第"+(i+1)+"个学生的ID,姓名,成绩:"); Scannerin=newScanner(System.in); try{ Stringstr=in.nextLine(); Stringdata[]=str.split(""); for(intj=0;j<3;j++) { write.write(data[j]); write.newLine(); } }catch(IOExceptione){ //TODO自动生成的catch块 e.printStackTrace(); } } try{ write.close(); filewrite.close(); }catch(IOExceptione){ //TODO自动生成的catch块 e.printStackTrace(); } } publicvoidget() { intsum=0; doubleave; try{ fileread=newFileReader(file); }catch(FileNotFoundExceptione){ //TODO自动生成的catch块 e.printStackTrace(); } read=newBufferedReader(fileread); for(inti=0;i<3;i++) { stu[i]=newStudent(); try{ stu[i].setId(Integer.parseInt(read.readLine())); stu[i].setName(read.readLine()); stu[i].setScore(Integer.parseInt(read.readLine())); }catch(Exceptione){ //TODO自动生成的catch块 e.printStackTrace(); } } for(inti=0;i<3;i++) { sum+=stu[i].getScore(); } ave=sum*1.0/3; System.out.println("学生的平均成绩为:"+ave); try{ read.close(); fileread.close(); }catch(IOExceptione){ //TODO自动生成的catch块 e.printStackTrace(); } } publicstaticvoidmain(String[]args) { project2pro=newproject2(); pro.put(); pro.get(); } }
总结:
这样我们就可以在项目当中,根据项目需求自己来定义想要的数组.