一 案列引入
自定义学生类:包含姓名,年龄,成绩属性.私有成员变量,生成无参,有参构造方法,生成get/set方法. 创建5个学生放到 ArrayList中.使用迭代器获取每个学生信息.统计总分,平均分,最高分,最低分并输出 采用技术:ArrayList集合 迭代器
二 代码实现
public static void getMaxAndMinScore ( ArrayList< Student> lists) {
if ( lists != null && lists. size ( ) > 0 ) {
double maxScore = lists. get ( 0 ) . getScore ( ) ;
double minScore = lists. get ( 0 ) . getScore ( ) ;
Iterator< Student> it = lists. iterator ( ) ;
while ( it. hasNext ( ) ) {
if ( it. next ( ) . getScore ( ) > maxScore) {
maxScore = it. next ( ) . getScore ( ) ;
}
if ( it. next ( ) . getScore ( ) < minScore) {
minScore = it. next ( ) . getScore ( ) ;
}
}
System. out. println ( "最高分为:" + maxScore+ "/n" + "最低分为:" + minScore) ;
return ;
}
System. out. println ( "学生信息表无内容" ) ;
}
Exception in thread "main" java. util. NoSuchElementException
at java. base/ java. util. ArrayList$Itr. next ( ArrayList. java: 999 )
at heima. homework. practice02. StuTest. getMaxAndMinScore ( StuTest. java: 69 )
at heima. homework. practice02. StuTest. main ( StuTest. java: 26 )
三 异常原因分析:
while ( it. hasNext ( ) ) {
if ( it. next ( ) . getScore ( ) > maxScore) {
maxScore = it. next ( ) . getScore ( ) ;
}
if ( it. next ( ) . getScore ( ) < minScore) {
minScore = it. next ( ) . getScore ( ) ;
}
}
it.hasNext()询问是否有下一个元素,返回true执行语句体,在循环中第一个if中调用了it.next()获取下一个元素然后移位,而第二个if中再次调用it.next()获取下一个元素(相对而言),并移位,相当于一次询问两次移位,而第二次移位并没有询问而直接获取,如果当前位置没有元素值就会出现java.util.NoSuchElementException异常。
四 解决方法
方式一(获取第二个迭代器,分别迭代出最大最小值,但不推荐)
Iterator< Student> it = lists. iterator ( ) ;
Iterator< Student> it2 = lists. iterator ( ) ;
while ( it. hasNext ( ) ) {
if ( it. next ( ) . getScore ( ) > maxScore) {
maxScore = it. next ( ) . getScore ( ) ;
}
}
while ( it2. hasNext ( ) ) {
if ( it2. next ( ) . getScore ( ) < minScore) {
minScore = it2. next ( ) . getScore ( ) ;
}
}
最高分为:100.0
最低分为:56.0
方式二:先调用it.next()获取出ArrayList集合中的对象再进行最大最小值判断,这样遍历的都是同一个对象,一次询问,一次移位。
Iterator< Student> itr = students. iterator ( ) ;
while ( itr. hasNext ( ) ) {
Student student = itr. next ( ) ;
if ( maxScore < student. getScore ( ) ) {
maxScore = student. getScore ( ) ;
} else if ( minScore > student. getScore ( ) ) {
minScore = student. getScore ( ) ;
}
}
最高分为:100.0
最低分为:56.0
五 总结
在使用迭代器进行取值时应先用it.hasNext()进行询问是否有下一个元素,然后通过it.next()进行取值后并移位,但是切记调用一次就会移位一次,如果进行再次移位没有通过it,hasNext()询问,很可能取不到元素而爆出 java.util.NoSuchElementException异常,如果要对获取出的同一个元素进行操作,可以先用一个变量保存该对象后进行操作。