如何让我的扫描仪流只读取
中的整数Jane 354
Jill 546
Jenny 718
Penny 125
扫描程序方法nextLine()
读取了名称和数字,所以我想我可以解析它,但我想知道nextInt()
是否有办法跳过这个名字并且只读取数字,因为当它看到它以String
开始时它会立即失败。
答案 0 :(得分:0)
如何使用next()
,忽略其结果,然后使用nextInt()
?如果您的所有行都是您在问题中提供的格式,那么这应该完全符合您的要求。
答案 1 :(得分:0)
你可以调用scanner.next()并且不用它来跳过字符串,例如:
// Scanner sc;
while(sc.hasNextLine()){
sc.next(); //Skip string
int number = sc.nextInt();
}
答案 2 :(得分:0)
您也可以使用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));
}
答案 3 :(得分:0)
你可以做这样的事情
Scanner read = new Scanner(new File("some file here"));
while(read.hasNext()){
if(read.next() instanceof Integer){
System.out.println(read.next());
}
}