黑马程序员技术交流社区
标题:
代码79行一直提示数组越界异常,怎么回事
[打印本页]
作者:
571568202
时间:
2015-9-15 18:14
标题:
代码79行一直提示数组越界异常,怎么回事
import java.io.*;
import java.util.*;
//定义学生类
class Student implements Comparable<Student>
{
private String name ;
private int ma,cn,en;
private int sum;
Student (String name,int ma,int cn,int en )
{
this.name=name;
this.ma=ma;
this.cn=cn;
this.en=en;
sum=ma+cn+en;
}
public int compareTo(Student s )
{
int num = new Integer(this.sum).compareTo( new Integer (s.sum));
if(num==0)
return this.name.compareTo(s.name);
return num;
}
public String getName()
{
return name;
}
public int getSum()
{
return sum;
}
public int hashCode()
{
return this.name.hashCode()+sum*78;
}
public boolean equals (Object obj )
{
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配");
Student s = (Student ) obj;
return this.name.equals(s.name) && this.sum == s.sum ;
}
public String toString ()
{
return "Student ["+this.name+","+this.ma+","+this.cn+","+this.en+"]";
}
}
class StudentInfoTool
{
public static Set<Student> getStudents () throws Exception
{
BufferedReader bufr =new BufferedReader ( new InputStreamReader (System.in));
String line = null;
Set<Student> stus = new TreeSet<Student> ();
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[3]));
stus.add(stu);
}
bufr.close();
return stus;
}
public static void writeToFile(Set<Student> stus) throws Exception
{
BufferedWriter bufw = new BufferedWriter ( new FileWriter ("stuentinfo.txt"));
for(Student stu : stus )
{
bufw.write(stu.toString ());
bufw.write(stu.getSum());
bufw.newLine();
bufw.flush();
}
bufw.close();
}
}
class StudentInfoTest
{
public static void main(String[] args) throws Exception
{
Set <Student> set= StudentInfoTool.getStudents ();
StudentInfoTool.writeToFile(set);
}
}
复制代码
作者:
Coolman
时间:
2015-9-15 18:14
79行没有问题,问题出现在结束输入的条件上。字符串切割以后,你可以输出一下看看切割以后字符串数组里存了什么,增强for遍历输出一下字符串数组info做测试,按理说,你输入over是直接结束循环,不应该打印over出来的,问题就出现在判断条件"over "over后面多个了空格,也是醉了~~~
作者:
菊花爆满山
时间:
2015-9-15 19:11
2楼说的对的
作者:
夸克
时间:
2015-9-15 19:32
曾经我也遇到这个问题,哈哈哈哈,容我笑一下!
当时怎么也想不明白,代码逻辑非常正确啊,为什么就出问题呢,后来我发现
是因为“over”后边多了个空格,就是这句里 if("over ".equals(line))
很明显,你也多写了个空格,导致你输入over根本不匹配“over +空格”,不能break出去,自然后边你懂得了
分拿来吧少年
作者:
15173139267
时间:
2015-9-15 19:33
1楼那个人是对的.主要是你over 后面多了一个空格.你在控制台输入的时候, 你只输入了"over",并不是输入的“over ".前面的两个over看懂了没。 区别在于"空格"上面.所以报数组.
QQ图片20150915193341.png
(167.74 KB, 下载次数: 15)
下载附件
2015-9-15 19:33 上传
作者:
夸克
时间:
2015-9-15 19:34
我复制你的代码,然后删掉空格试了试,就不会报错了
作者:
瑞雪雄起
时间:
2015-9-16 02:08
你的Over多了个空格
其实这样也可以
String line = bufr.readLine().trim();
while(!line.isEmpty())
{
String [] info =line.split(",");
line=bufr.readLine().trim();
}
作者:
瑞雪雄起
时间:
2015-9-16 02:10
长度为0的字符串,一定不是null的
作者:
那风景如花
时间:
2015-9-16 13:15
你的Over多了个空格
作者:
洛邑王澈
时间:
2015-9-16 21:02
话说我也经常多空格
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2