Answer to Question #285991 in Java | JSP | JSF for kkkkkk

Question #285991

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

1
Expert's answer
2022-01-10T07:38:31-0500
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);
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog