简体   繁体   English

读取扫描仪中的数字

[英]Read only numbers from scanner

Imagine there is Scanner passes any String input such as "11 22 ab 22" and the method should calculate the total sum of all of the numbers (55 for the mentiond example). 想象一下,扫描程序传递了任何字符串输入,例如“ 11 22 ab 22”,并且该方法应该计算所有数字的总和(上述示例为55)。 I've coded something here but I'm not able to skip strings. 我已经在此处进行了编码,但是无法跳过字符串。 Could anyone help me with that? 有人可以帮我吗?

System.out.println("Please enter any words and/or numbers: ");
String kbdInput = kbd.nextLine();
Scanner input = new Scanner(kbdInput);
addNumbers(input);  

public static void addNumbers(Scanner input) {
    double sum = 0;
    while (input.hasNextDouble()) {
        double nextNumber = input.nextDouble();
        sum += nextNumber;
    }
    System.out.println("The total sum of the numbers from the file is " + sum);

}

To be able to bypass non-numeric input, you need to have your while loop look for any tokens still on the stream, not just double s. 为了能够绕过非数字输入,您需要让while循环查找仍在流中的所有令牌,而不仅仅是double

while (input.hasNext())

Then, inside, the while loop, see if the next token is a double with hasNextDouble . 然后,在while循环内部,使用hasNextDouble查看下一个标记是否为double If not, you still need to consume the token with a call to next() . 如果没有,您仍然需要通过调用next()来消耗令牌。

if (input.hasNextDouble())
{
   double nextNumber = input.nextDouble();
   sum += nextNumber;
}
else
{
   input.next();
}

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

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