1.java创建自定义类数组方法:
1
2
3
4
5
|
Student []stu = new Student[ 3 ]; for ( int i = 0 ; i < 3 ; i ++) { stu[i] = new Student(); } |
2.否则会提示空指针异常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
|
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(); } } |
总结:
这样我们就可以在项目当中,根据项目需求自己来定义想要的数组.