java 创建自定义数组
更新时间:2016年07月07日 12:01:53 投稿:lqh
本篇文章是关于java 如何自己创建自定义数组,这里给大家一个小实例,希望能帮助有所需要的同学
1.java创建自定义类数组方法:
Student []stu = new Student[3]; for(int i = 0; i < 3; i ++) { stu[i] = new Student(); }
2.否则会提示空指针异常
package project; import java.io.*; import java.util.Scanner; class Student { private int id; private String name; private int score; public void setId(int id) { this.id = id; } public int getId() { return this.id; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setScore(int score) { this.score = score; } public int getScore() { return this.score; } } public class project2 { File file = new File("E:/data.txt"); FileWriter filewrite = null; BufferedWriter write = null; FileReader fileread = null; BufferedReader read = null; Student []stu = new Student[3]; public void put() { try { filewrite = new FileWriter(file); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } write = new BufferedWriter(filewrite); for(int i = 0; i < 3; i ++) { System.out.println("请输入第" + (i + 1) + "个学生的ID,姓名,成绩:"); Scanner in = new Scanner(System.in); try { String str = in.nextLine(); String data[] = str.split(" "); for(int j = 0; j < 3; j++) { write.write(data[j]); write.newLine(); } } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } try { write.close(); filewrite.close(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } public void get() { int sum = 0; double ave; try { fileread = new FileReader(file); } catch (FileNotFoundException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } read = new BufferedReader(fileread); for(int i = 0; i < 3; i ++) { stu[i] = new Student(); try { 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(); } } for(int i = 0; i < 3; i ++) { sum += stu[i].getScore(); } ave = sum * 1.0/3; System.out.println("学生的平均成绩为:" + ave); try { read.close(); fileread.close(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } public static void main (String []args) { project2 pro = new project2(); pro.put(); pro.get(); } }
总结:
这样我们就可以在项目当中,根据项目需求自己来定义想要的数组.
相关文章
深入了解HttpClient的ResponseHandler接口
这篇文章主要为大家介绍了深入了解HttpClient的ResponseHandler接口,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-10-10详解SpringBoot2 使用Spring Session集群
这篇文章主要介绍了SpringBoot2 使用Spring Session集群,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值 ,需要的朋友可以参考下2019-04-04Java中字符数组、String类、StringBuffer三者之间相互转换
这篇文章主要介绍了Java中字符数组、String类、StringBuffer三者之间相互转换,需要的朋友可以参考下2018-05-05MyEclipse去除网上复制下来的代码带有的行号(正则去除行号)
这篇文章主要介绍了MyEclipse去除网上复制下来的代码带有的行号(正则去除行号)的相关资料,需要的朋友可以参考下2017-10-10
最新评论