do while loop
2. Write a java program that reads in a list of int values one per line
and outputs their sum as well as the numbers read with each number.
Your programs will ask the user how many integers there will be, and
fill the table with the integers input.
Sample output:
How many numbers will you enter?
2
Enter 2 integers one per line:
20
30
The sum is 50
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int howMany;
System.out.println("How many numbers will you enter?");
while (true) {
try {
howMany = input.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("The entered number is incorrect, please try again...");
input.next();
}
}
int sum = 0;
System.out.println("Enter " + howMany + " integers one per line:");
for (int i = 0; i < howMany; i++) {
while (true) {
try {
sum += input.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("The entered number is incorrect, please try again...");
input.next();
}
}
}
System.out.println("The sum is " + sum);
}
}
Comments
Leave a comment