HackerRank 30 Days of Code - 16. Exceptions - String to Integer

hh9n

Problem

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

Note You must use the String-to-Integer and exception handling constructs built into your submission language.
INPUT
3
za
OUTPUT
3
Bad String

Solution (Java)

public class Solution {
  public static void main(String[] args) throws IOException {
    try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
      String string = bufferedReader.readLine().trim();
      printStringToInteger(string);
    }
  }
  
  public static void printStringToInteger(String strValue) {
    try {
      System.out.println(Integer.parseInt(strValue));
    } catch (NumberFormatException e) {
      System.out.println("Bad String");
    }
  }
}

發佈留言