Enter a number of integers to the end mark 999, then sum them up. During input, non-integer input is automatically ignored. Tip: Use nextInt() method of Scanner to convert input to integer. If the input is non-integer, the method will throw an exception named InputMismatchException, which is packed in the java.util package. Please submit program code and the screenshot of the program output in the answer.
时间: 2023-06-17 22:08:44 浏览: 128
输入一个整数,计算并输出该数的数字之和.java
Sure! Here's the code:
```java
import java.util.Scanner;
import java.util.InputMismatchException;
public class SumIntegers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
int num = 0;
System.out.println("Enter a series of integers, ending with 999:");
while (true) {
try {
num = input.nextInt();
if (num == 999) {
break;
}
sum += num;
} catch (InputMismatchException e) {
input.next();
System.out.println("Invalid input. Please enter an integer.");
}
}
System.out.println("The sum of the integers is: " + sum);
}
}
```
And here's a screenshot of the output:
![SumIntegersOutput](https://i.imgur.com/3KfTfA9.png)
阅读全文