Challenge: Add Up the Good Numbers

Lab Java Intermediate 20 points

Read n, then n lines. Some lines are whole numbers, others are not. Add up the numbers, and count the bad lines. Print Sum: <sum> and Skipped: <count>.

Input

First n, then n lines of text.

Output

Sum: <sum>
Skipped: <count>

Example

Input

5
10
abc
-3
4.5
20

Output

Sum: 27
Skipped: 2
Sample input available Sample output available
Editor
Java

Hints

Read every line with nextLine() so bad lines don't break the Scanner.

Put the parseInt inside try, and count in the catch.

Solution explanation

The try/catch is inside the loop, so one bad line only skips that line.

Show solution
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine().trim());
        int sum = 0, skipped = 0;
        for (int i = 0; i < n; i++) {
            String line = sc.nextLine().trim();
            try {
                sum += Integer.parseInt(line);
            } catch (NumberFormatException e) {
                skipped++;
            }
        }
        System.out.println("Sum: " + sum);
        System.out.println("Skipped: " + skipped);
    }
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD