黑马程序员技术交流社区
标题:
数组下标问题
[打印本页]
作者:
纷飞尽
时间:
2013-12-18 17:25
标题:
数组下标问题
有一个学生类
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数组下标异常,什么原因?
作者:
四五六七八
时间:
2013-12-18 17:43
Student stu=new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[4]));
这句话 数组下标你有一个是4,,,,应该是3
作者:
刘松703
时间:
2013-12-18 19:10
我看了一遍,你的student类中,没有重写toString()方法;这个方法是需要重写的
作者:
刘松703
时间:
2013-12-18 19:13
可能你是没写全类的方法把,哈哈哈,还有2楼说的也对,你太粗心了
作者:
纷飞尽
时间:
2013-12-18 22:29
我 把这句话改成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这个错误!为什么
作者:
小骗子
时间:
2013-12-19 19:39
你的程序在没有任何输入的情况,line值是空的,然后你去定义Info[],这个时候的Info是怎么取的?
编译是通不过的。
如果可以确定split成几段,直接定义成固定长度的数组应该问题不大。
作者:
kun1990
时间:
2013-12-19 21:16
数组越界问题
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2