OCJP之Scanner使用iterator调next()不当会进入死循环

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() + " ");
		 }
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值