HR30 Day 16: Exceptions - String to Integer

1 개요[ | ]

HR30 Day 16: Exceptions - String to Integer
해커랭크 30 Days of Code
문제 풀이
10-19 Day e
HR30 Day 10: Binary Numbers

HR30 Day 11: 2D Arrays

HR30 Day 12: Inheritance

HR30 Day 13: Abstract Classes

HR30 Day 14: Scope

HR30 Day 15: Linked List

HR30 Day 16: Exceptions - String to Integer

HR30 Day 17: More Exceptions

HR30 Day 18: Queues and Stacks

HR30 Day 19: Interfaces

2 Java[ | ]

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String S = in.next();
        try {
            int num = Integer.parseInt(S);
            System.out.println(num);
        } catch (NumberFormatException e) {
            System.out.println("Bad String");
        }
    }
}

3 PHP[ | ]

<?php
$handle = fopen ("php://stdin","r");
fscanf($handle,"%s",$S);
echo is_numeric($S) ? $S : 'Bad String';
<?php
$handle = fopen ("php://stdin","r");
fscanf($handle,"%s",$S);
try {
    new SplFixedArray($S);
    echo $S;
} catch (TypeError $e) {
    echo 'Bad String';
}
<?php
$handle = fopen ("php://stdin","r");
fscanf($handle,"%s",$S);
function throwMyException() {
    throw new Exception('Bad String');
}
try {
    ($S>0)? 0 : throwMyException();
    echo $S;
} catch (Exception $e) {
    echo $e->getMessage();
}
<?php
$handle = fopen ("php://stdin","r");
fscanf($handle,"%s",$S);
try {
    new ReflectionClass('ReflectionClass'.!is_numeric($S));
    echo $S;
} catch (Exception $e) {
    echo 'Bad String';
}
<?php
$handle = fopen ("php://stdin","r");
fscanf($handle,"%s",$S);
try {
    new ReflectionClass('ReflectionClass'. ((int)$S.'' !== $S));
    echo $S;
} catch (Exception $e) {
    echo 'Bad String';
}

4 Python[ | ]

#!/bin/python3
import sys

S = input().strip()

try:
    num = int(S)
    print(num)
except ValueError:
    print("Bad String")

5 Ruby[ | ]

#!/bin/ruby

S = gets.strip

begin
    puts Integer(S)
rescue
    puts 'Bad String'
end
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}