想象一下,Scanner传递任何字符串输入,如"11 22 ab 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);
}
Run Code Online (Sandbox Code Playgroud)