java之创建自定义类数组
来源:互联网 发布:软件项目启动通知单 编辑:程序博客网 时间:2024/06/10 19:15
java创建自定义类数组方法:
Student []stu = new Student[3];
for(int i = 0; i < 3; i ++)
{
stu[i] = new Student();
}
否则会提示空指针异常
eg:
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();}}
- java之创建自定义类数组
- Java自定义类数组的创建和使用
- 第二十、Java之static自定义数组工具类
- 创建自定义类的对象数组
- java编程题之自定义动态数组
- JAVA自定义数组工具类
- 创建自定义java类需要注意的
- java中创建自定义类加载器
- 关于java自定义异常类的创建
- java版微信公众号开发之自定义菜单的创建
- 【Java学习之代码学习】 Prog36_自定义整型数组
- Javascript数组之创建
- 用Java创建数组工具类ArrayTool
- Java使用Array类创建多维数组
- 关于JAVA类对象数组的创建
- JAVA“类”数组的创建与调用
- java创建对象数组
- java动态创建数组
- linux架构
- js实现用自符串替换占位符{0} {1} {2} 等
- Apache+php+mysql在windows下的安装与配置图解
- android 电容屏(四):驱动调试之驱动程序分析篇 -- FocalTech
- awk技巧-!a[$0]++
- java之创建自定义类数组
- 微软正在寻找cookie的代替品
- 小数点后的位数个数
- Android 中多点触摸协议
- Qt modal & modalless
- loadrunner 小知识累积
- Web服务器父与子 Apache和Tomcat区别
- COM编程入门(一)
- SVN Working copy locked (SVN无法更新解决办法)