java 創(chuàng)建自定義數(shù)組
1.java創(chuàng)建自定義類數(shù)組方法:
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) + "個(gè)學(xué)生的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("學(xué)生的平均成績?yōu)椋? + 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(); } }
總結(jié):
這樣我們就可以在項(xiàng)目當(dāng)中,根據(jù)項(xiàng)目需求自己來定義想要的數(shù)組.
相關(guān)文章
深入了解HttpClient的ResponseHandler接口
這篇文章主要為大家介紹了深入了解HttpClient的ResponseHandler接口,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10idea遠(yuǎn)程debug調(diào)試部署在tomcat上項(xiàng)目
本文主要介紹了idea遠(yuǎn)程debug調(diào)試部署在tomcat上項(xiàng)目,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08詳解SpringBoot2 使用Spring Session集群
這篇文章主要介紹了SpringBoot2 使用Spring Session集群,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2019-04-04Java中字符數(shù)組、String類、StringBuffer三者之間相互轉(zhuǎn)換
這篇文章主要介紹了Java中字符數(shù)組、String類、StringBuffer三者之間相互轉(zhuǎn)換,需要的朋友可以參考下2018-05-05MyEclipse去除網(wǎng)上復(fù)制下來的代碼帶有的行號(正則去除行號)
這篇文章主要介紹了MyEclipse去除網(wǎng)上復(fù)制下來的代碼帶有的行號(正則去除行號)的相關(guān)資料,需要的朋友可以參考下2017-10-10