Challenge: Add Up the Good Numbers
Completed
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
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
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module