Safe Parsing
Completed
Read n tokens. For each print the number doubled, or invalid: TOKEN if it isn't an integer (catch NumberFormatException).
Input
n, then n tokens.
Output
n lines.
Example
Input
4 5 abc -3 2.5
Output
10 invalid: abc -6 invalid: 2.5
Editor
Java
Hints
Integer.parseInt throws NumberFormatException for bad text.
Solution explanation
Catching a specific exception type handles the expected failure and lets real bugs surface.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
String token = sc.next();
try {
System.out.println(Integer.parseInt(token) * 2);
} catch (NumberFormatException e) {
System.out.println("invalid: " + token);
}
}
}
}