Java Day 16 - Exceptions - String to Integer



Read a string, S, and print its integer value; if S cannot be converted to an integer, print Bad String.



  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6. public class Solution {
  7. public static void main(String[] args) {
  8. Scanner in = new Scanner(System.in);
  9. String string = in.next();
  10. in.close();
  11. try {
  12. Integer integer = Integer.parseInt(string);
  13. System.out.println(integer);
  14. } catch (NumberFormatException numberFormatException) {
  15. System.out.println("Bad String");
  16. }
  17. }
  18. }