-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay16-Exceptions-String-to-Integer
More file actions
34 lines (26 loc) · 997 Bytes
/
Day16-Exceptions-String-to-Integer
File metadata and controls
34 lines (26 loc) · 997 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Problem:
Objective
Today, we're getting started with Exceptions by learning how to parse an integer from a string and print a custom error message.
Check out the Tutorial tab for learning materials and an instructional video!
Task
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.
If you attempt to use loops/conditional statements, you will get a 0 score.
Solution:
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 i = Integer.parseInt(S.trim());
System.out.println(i);
} catch (NumberFormatException nfe) {
System.out.println("Bad String");
}
}
}