- Java code
import java.util.Scanner;public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); sc.useDelimiter(","); while (sc.hasNext()) { System.out.println(sc.next()); } sc.close(); }}
输入 1,2,3,4,5
结果是
1
2
3
4
最后那位怎么不见了
------解决方案--------------------
5后面要加,
------解决方案--------------------
当Scanner从System.in中读数据时,调用next()或hasnext()时,如果没数据了,系统会陷入等待,等你从键盘录入。换句话说,你把hasnext()写到while循环里,程序一定会因为数据不足而陷入停顿的
Scanner从System.in中读数据,要么你明确的知道你会输入几个数据,就调用几个next()
要么你读入一行,再对这行进行分解,例如:
- Java code
Scanner sc = new Scanner(System.in); String s = sc.nextLine(); Scanner Scanner = new Scanner(s); Scanner.useDelimiter(","); while(Scanner.hasNext()) { System.out.println(Scanner.next()); }