欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 创建自定义数组

程序员文章站 2024-03-13 11:39:45
1.java创建自定义类数组方法: student []stu = new student[3]; for(int i = 0; i < 3; i ++)...

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

    总结:

             这样我们就可以在项目当中,根据项目需求自己来定义想要的数组.