简体   繁体   English

如何在Java中也从包含字符串的文件中扫描整数

[英]How to scan integers from a file containing Strings too in Java

How would I get my scanner stream to read just the integers in 我如何让我的扫描仪流只读取其中的整数

Jane    354
Jill    546
Jenny   718
Penny   125

The Scanner method nextLine() read both the name, and the number, so I suppose I could just parse it out, but I wanted to know if there were a way for nextInt() to skip the name and only read the numbers because it fails right away when it sees that it starts with a String . Scanner方法nextLine()读取名称和数字,因此我想可以将其解析出来,但是我想知道nextInt()是否有一种跳过名称并仅读取数字的方法,因为它看到以String开头时立即失败。

How about using next() , ignore its result and then use nextInt() ? 如何使用next() ,忽略其结果然后使用nextInt()呢? This should do exactly what you need if all your lines are in format you presented in your question. 如果您所有的行都采用问题中提出的格式,则此操作完全可以满足您的需求。

You can just call scanner.next() and do nothing with it to skip the string, for instance: 您可以只调用scanner.next(),而对其不执行任何操作以跳过字符串,例如:

// Scanner sc;
while(sc.hasNextLine()){
    sc.next(); //Skip string
    int number = sc.nextInt();
}

You could also use scanner.nextLine() and then grab the int with a reg ex matcher 您也可以使用scanner.nextLine(),然后使用正则表达式匹配器获取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));
}

You could do something like this 你可以做这样的事情

Scanner read = new Scanner(new File("some file here"));
while(read.hasNext()){
    if(read.next() instanceof Integer){
        System.out.println(read.next());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM