Input is rarely clean. Read lines that should be whole numbers, use the good ones and count the bad ones.
What to build
A program that averages the valid whole numbers among its input lines.
Requirements
- Read n, then n lines. Parse each with
Integer.parseInt(after trimming spaces); lines that throwNumberFormatExceptionare skipped. - Print
average: Awith two decimals, oraverage: nonewhen no line is valid, thenskipped: K.
Input
Line 1: n. Then n lines.
Output
Two lines.
Constraints
1 ≤ n ≤ 100; valid numbers are between -10^6 and 10^6.
Example
Input:
4
10
abc
20
5
Output:
average: 11.67
skipped: 1
Why it works
Catching NumberFormatException around each parse lets one bad line be counted and skipped instead of stopping the whole program.
Examples
Example 1 · Input
4 10 abc 20 5
Expected output
average: 11.67 skipped: 1
Example 2 · Input
2 x 3.5
Expected output
average: none skipped: 2
Hints
Hint 1
Put Integer.parseInt inside try and count the lines that throw NumberFormatException.
Hint 2
Format the average with String.format("%.2f", ...).
Solution
Show one correct solution (try it yourself first)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine().trim());
long sum = 0;
int count = 0;
int skipped = 0;
for (int i = 0; i < n; i++) {
String line = in.nextLine().trim();
try {
sum += Integer.parseInt(line);
count++;
} catch (NumberFormatException e) {
skipped++;
}
}
if (count == 0) {
System.out.println("average: none");
} else {
System.out.println("average: " + String.format("%.2f", (double) sum / count));
}
System.out.println("skipped: " + skipped);
}
}