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