-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckIfStringIsNumeric.java
More file actions
61 lines (52 loc) · 1.9 KB
/
Copy pathCheckIfStringIsNumeric.java
File metadata and controls
61 lines (52 loc) · 1.9 KB
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
58
59
60
61
/**
* Created by akumar6 on 7/19/15.
*/
public class CheckIfStringIsNumeric {
public static void main(String[] args) {
System.out.println(isNumeric("123"));
System.out.println(isNumeric("-123"));
System.out.println(isNumeric("-123.12"));
System.out.println(isNumeric("-,."));
System.out.println(isNumeric("1,123,345"));
System.out.println(isNumeric("a.1,123,345"));
System.out.println(isNumeric("ab1,123,345"));
}
private static boolean isNumeric(String s) {
return s.matches("^([+-]?\\d*\\.?\\d*)$");
}
private static boolean isIPAddress(String s) {
return s.matches("^(\\d*\\.?\\d*)$");
}
public static boolean isNumber(String toTest) {
boolean isNegativeFoundAlready = false;
boolean isDecimalPointFoundAlready = false;
for (int i=0; i < toTest.length(); i++) {
if (!"0123456789-.".contains(new String(new char[]{toTest.charAt(i)}))) {
return false;
} else {
if ('-' == toTest.charAt(i) && i != 0) {
return false;
}
if ('-' == toTest.charAt(i) && (i == toTest.length() - 1)) {
return false;
}
if ('-' == toTest.charAt(i) && isNegativeFoundAlready) {
return false;
}
if ('-' == toTest.charAt(i)) {
isNegativeFoundAlready = true;
}
if ('.' == toTest.charAt(i) && isDecimalPointFoundAlready) {
return false;
}
if ('.' == toTest.charAt(i)) {
isDecimalPointFoundAlready = true;
}
if ('.' == toTest.charAt(i) && (i == toTest.length() - 1)) {
return false;
}
}
}
return true;
}
}