A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 纷飞尽 中级黑马   /  2013-12-18 17:25  /  1230 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

有一个学生类
  private String name;
    private int chinese;
    private int math;
    private int en;
    private int sum;
  public Student(String name,int chinese,int math,int en)
    {
            this.name=name;
            this.chinese=chinese;
            this.math=math;
            this.en=en;
            sum=chinese+math+en;
    }
在定义一个操作学生的类,
public static Set<Student> getStudents(Comparator<Student>cmp) throws IOException
      {  
              //键盘录入学生信息
             System.out.println("请输入学生成绩:");
              BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
          String line=null;
          Set<Student> stus=null;
          if(cmp==null)
                 stus=new TreeSet<Student>();
         else
              stus=new TreeSet<Student>(cmp);
          while((line=bufr.readLine())!=null)
          {
                  if("over".equals(line))
                         break;
             String[]info=line.split(",");
                 Student stu=new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[4]));
             stus.add(stu);
          }
          bufr.close();
          return stus;
      }
      //写到文件中
      public static void writeFile(Set<Student>stus) throws IOException
      {
              BufferedWriter bufw = new BufferedWriter(new FileWriter("studentInfo.txt"));
          for(Student stu:stus)
          {
                  bufw.write(stu.toString()+"\t");
                  bufw.write(stu.getSum());
                  bufw.newLine();
                  bufw.flush();
          }
          bufw.close();
      }
在测试的时候报:java.lang.ArrayIndexOutOfBoundsException数组下标异常,什么原因?

评分

参与人数 1技术分 +1 收起 理由
乔兵 + 1

查看全部评分

6 个回复

倒序浏览
Student stu=new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[4]));
这句话  数组下标你有一个是4,,,,应该是3   
回复 使用道具 举报
我看了一遍,你的student类中,没有重写toString()方法;这个方法是需要重写的
回复 使用道具 举报
可能你是没写全类的方法把,哈哈哈,还有2楼说的也对,你太粗心了
回复 使用道具 举报
我 把这句话改成Student stu=new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[3]))这样后,还是会报
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1这个错误!为什么
回复 使用道具 举报
你的程序在没有任何输入的情况,line值是空的,然后你去定义Info[],这个时候的Info是怎么取的?
编译是通不过的。
如果可以确定split成几段,直接定义成固定长度的数组应该问题不大。

评分

参与人数 1技术分 +1 收起 理由
乔兵 + 1

查看全部评分

回复 使用道具 举报
kun1990 中级黑马 2013-12-19 21:16:19
7#
数组越界问题
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马