1.Handle bad input
AdvancedFor each of "42", "abc" and " 7 ", try Integer.parseInt and print the number or invalid. Then fix the third input by stripping spaces.
Show hint
parseInt throws NumberFormatException for text that is not exactly a number, including surrounding spaces.
Show solution
public class Main {
public static void main(String[] args) {
for (String text : new String[] {"42", "abc", " 7 "}) {
try {
System.out.println(Integer.parseInt(text));
} catch (NumberFormatException e) {
System.out.println("invalid: [" + text + "]");
}
}
System.out.println(Integer.parseInt(" 7 ".strip()));
}
}42
invalid: [abc]
invalid: [ 7 ]
7