您的位置:首页 > 其它

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() + " ");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐