如何让我的扫描程序流只读取整数
Jane 354
Jill 546
Jenny 718
Penny 125
Scanner 方法nextLine()
读取名称和数字,所以我想我可以解析它,但我想知道是否有办法让nextInt()
跳过名称而只读取数字,因为它在看到它以String
开头时立即失败。
使用
next()
怎么样,忽略它的结果,然后使用 nextInt()
?如果您的所有行都是您在问题中提出的格式,这应该完全符合您的需求。
你可以只调用 scanner.next() 并且不对它执行任何操作来跳过字符串,例如:
// Scanner sc;
while(sc.hasNextLine()){
sc.next(); //Skip string
int number = sc.nextInt();
}
你也可以使用 scanner.nextLine(),然后用 reg ex matcher 抓取 int
String mydata = scanner.nextLine();
Pattern pattern = Pattern.compile([0-9]+);
Matcher matcher = pattern.matcher(mydata);
if (matcher.find()){
int num = Integer.parseInt(matcher.group(1));
}
你可以做这样的事情
Scanner read = new Scanner(new File("some file here"));
while(read.hasNext()){
if(read.next() instanceof Integer){
System.out.println(read.next());
}
}