java 創立自界說數組。本站提示廣大學習愛好者:(java 創立自界說數組)文章只能為提供參考,不一定能成為您想要的結果。以下是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(); } }
總結:
如許我們便可以在項目傍邊,依據項目需求本身來界說想要的數組.