forked from ashoklathwal/Code-for-Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parseStrToInteger.java
57 lines (54 loc) · 1.67 KB
/
parseStrToInteger.java
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.*;
import java.lang.*;
class parseStrToInteger
{
//function which parse string to integer
public static int strToInt(String str)
{
//for checking negative numbers
boolean neg = false;
int start=0;
int number = 0;
if(str.charAt(0) == '-')
{
neg = true;
start = 1;
}
for(int i=start; i < str.length(); i++)
{
number *= 10;
number += str.charAt(i) - '0';// parsing
//number += (int)str.charAt(i); // casting
//System.out.println('a' - '0'); // output : 49 // parsing
//System.out.println((int)'a'); // output : 97 // casting
}
if(neg)
number = -number;
return number;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String str="abcd";
String StringThatCouldBeANumberOrNot = "26263He"; //will throw exception
String StringThatCouldBeANumber = "26263"; //will not throw exception
int foo1=0,foo2=0;
try {
foo1 = Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e)
{
//Will Throw exception!
//do something! anything to handle the exception.
}
try {
foo2 = Integer.parseInt(StringThatCouldBeANumber);
} catch (NumberFormatException e)
{
//No problem this time, but still it is good practice to care about exceptions.
//Never trust user input :)
//Do something! Anything to handle the exception.
}
System.out.println(foo1+" "+foo2);
System.out.println(strToInt(StringThatCouldBeANumberOrNot)+" "+strToInt(StringThatCouldBeANumber));
}
}