博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java类数组
阅读量:4029 次
发布时间:2019-05-24

本文共 2333 字,大约阅读时间需要 7 分钟。

java之创建自定义类数组
2013-12-06           来源:每天进步一点点 时间会让你成为巨人   
    

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();	}}

转载地址:http://tshbi.baihongyu.com/

你可能感兴趣的文章
Linux配置sendmail实现PHP发送邮件
查看>>
c++ 特性回顾
查看>>
网站注册的时候,烦人的生日年份选择的改进想法
查看>>
游戏开发两年记 之 工程和理论需双剑合璧
查看>>
Nachos中switch汇编源码分析
查看>>
游戏开发两年之产品逻辑鸡肋么?
查看>>
secureCRT和Xshell登录Ubuntu
查看>>
secureCRT和Xshell登录ubuntu
查看>>
Apache下c语言的cgi如何获得Get,Post参数
查看>>
protobuf的使用初探
查看>>
ngx_http分析
查看>>
搭建一个php学习框架mycake
查看>>
MVC模式概念
查看>>
大量拉取网络数据的策略总结
查看>>
php把一个格式化的文件转换为一个二维数组
查看>>
DOM学习
查看>>
php遍历一个指定文件夹
查看>>
CakePHP 的代码结构
查看>>
Magento 的目录结构
查看>>
mysql 常用命令
查看>>