OCJP之Scanner使用iterator调next()不当会进入死循环
2013-06-30 10:55
459 查看
Scanner类实现了Iterator接口,没有特殊的东西,但next()不抛异常,而是进入死循环
代码:
代码:
package com.ocjp.io; import java.util.Scanner; public class ScannerTest { public static void main(String[] args) { String s = "123 345 -45"; // String s = "123 345 x -45"; //when nextShort() = x, x cannot be converted into short, program enters infinite loop; // String s = "123 345 88888888 -45"; //when nextShort() = 88888888, it's beyond short scope, program enters infinite loop; Scanner sc = new Scanner(s); while(sc.hasNext()){ //指针或者流标,以空格作为分隔符,检查从指针开始,是否有值(token),hasNext()不会移动游标; if(sc.hasNextShort())//同理,hasNextShort不会移动游标,它仍然是从最开始读取到空格, // nextShort()移动指针,到下一个token; // 读到非法字符时,比如说,x, 8888888,这些都不能转成short, 它是进入死循环!!! System.out.print(sc.nextShort() + " "); // System.out.print(sc.nextShort() + " "); } } }
相关文章推荐
- for 循环使用不当导致死循环,CPU激增
- Iterator 循环 List 使用remove方法报错的分析与解决办法。
- iterator循环和反向迭代器的使用
- javascript中使用${}获取后台参数——防止页面进入死循环
- Java中Scanner的next和nextLine的使用以及区别
- 关于scanner输入的说明,nextLine、nextInt、next的使用说明、类数组定义的说明
- 如何使用s:iterator循环每4条数据换一次行的代码
- 使用strtuts2的iterator标签循环输出二维数组
- <s:iterator></s:iterator>循环指定输出,(status的方法使用)
- 使用<s:iterator>标签来循环遍历某一实体下的set集合数据
- 黑马程序员—Java编程基础+常量与变量+类型的转换+进制的转换+运算符+scanner的使用+程序流程结构控制+循环结构
- Scanner的next,nextint和nextLine的使用总结
- 如何使用迭代器iterator循环删除容器中的元素?
- 如何使用迭代器iterator循环删除容器中的元素?
- 使用strtuts2的iterator标签循环输出二维数组和嵌套集合
- Java学习之容器上(Collection接口常用方法,Iterator接口,使用foreach循环遍历Collection集合元素,Set集合通用知识(Hashset类,hashcode()与Lin
- 如何使用迭代器iterator循环删除容器中的元素?
- 集合框架(三)使用Iterator接口来遍历一个集合和使用for-each循环简化
- 关于Scanner对象的nextLine()和next()的使用
- Scanner的next,nextint和nextLine的使用总结