1
想象一下,扫描仪通过任何字符串输入,如“11 22 a b 22”,该方法应该计算所有数字的总和(例如55)。我在这里编写了一些东西,但我无法跳过字符串。任何人都可以帮助我吗?从扫描仪只读数
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);
}
这与http://stackoverflow.com/questions/2367381/extract-numbers-from-a-string-java非常相似 - 该解决方案可能适合您 – 2015-02-05 21:54:42