Reputation: 75
I enter a list into a JTextArea
, and when I push a button, it runs the method below. I need to check to see if str[i+1]
, str[i+2]
is a String
and not an int
.
public void readData(JTextArea input) {
String[] str = input.getText().split("\n");
for(int i =1; i< str.length; i= i+3) {
try {
Integer.parseInt(str[i]);
simulator.add(new Process(Integer.parseInt(str[i]), str[i+1],str[i+2]));
} catch(NumberFormatException e) {
System.out.println("Please enter an integer only " +
str[i] + " is not an integer");
}
}
}
Upvotes: 1
Views: 491
Reputation: 35481
You could have a function that tries to parse the string into an Integer
or a Double
and return true if it succeeded, or return false is an exception was thrown during parsing. Parsing into a Double
should be enough since all integer values are decimal values without the .0
public static boolean isNumber(String s) {
try {
Double.parseDouble(s);
/* Use Integer.parseInt(s) instead, if
you want to check if the String s
is an Integer */
} catch(NumberFormatException e) { // string is not a number
return false;
}
return true;
}
Then you can say if(!isNumber(str))
to check if the String
str is not a number.
Alternatively, you could make the isNumber()
be a isNotNumber()
by swapping the return false
and return true
statements.
If you don't want to use exceptions, a different approach would be the following. Since we know a valid number can only contain digits and at most 1 dot for decimal point, we can iterate through the string and check for each character:
Here is a sample function:
public static boolean isNumber(String s) {
int dotCount = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != '.' && !Character.isDigit(s.charAt(i))) {
return false;
} else if(s.charAt(i) == '.') {
if(dotCount == 1) {
return false;
}
dotCount = 1;
}
}
return true;
}
EDIT: based on @MadProgrammer's suggestions:
A more general approach that will accept values separated with commas such as 1,35
or any amount of spaces within the number string like with 123 456 . 333
.
Approach:
Iterate through the string and check for each character:
So the code would look something like:
public static boolean isNumber(String s) {
int separatorCount = 0; // count dots and commas
char currChar;
s.trim(); // remove trailing and leading whitespace
for (int i = 0; i < s.length(); i++) {
currChar = s.charAt(i);
if (currChar != '.' && currChar != ',' && currChar != ' '
&& !Character.isDigit(currChar)) {
return false;
} else if (currChar == '.' || currChar == ',') {
if (separatorCount == 1) {
return false;
}
separatorCount = 1;
}
}
return true;
}
Another solution could use the NumberFormat
's parse()
method. However, this method only checks the beginning of the string (for example, for 12.3.3
it will return 12.3
) so we have to return false if the returned string doesn't equal the input string as well as if the ParseException
is thrown.
public static boolean isNumber(String s) {
try {
String newVal = NumberFormat.getInstance().parse(s).toString();
if (!newVal.equals(s)) {
return false;
}
} catch (ParseException e) {
return false;
}
return true;
}
NOTE: All of the methods should probably have a check if(s == null) { return false; }
for the input String
s to prevent a NullPointerException
Upvotes: 3
Reputation: 424983
This is a simple test that asserts there is at least one non numeric char:
if (str.matches(".*[^\\d.].*"))
the regex translates as "somewhere in the input there's a character that's not a digit or a dot"
Upvotes: 0
Reputation: 1685
You can try this simple regular expression to check if a string represents a number or not:-
String str = "12345";
System.out.println(str.matches("\\d+"));
Upvotes: 2
Reputation: 1622
Regex seems the best option. Here's a regex that will parse float and integers and currency values with comma as well.
String numberRex = "^([\\d]*\\.*\\d*|[\\d,]*\\.*\\d*)$";
"1234,455.43".matches(numberRex); // true
Upvotes: 0
Reputation: 347184
Your rules are sparse, you don't specify if things like ,
or .
are considered part of a number or not (1, 000.01
for example), also, you don't define if the value is allowed to contain numerical values or not, but...
Try parsing each value (or the concatenation of the two) using Integer.parseInt
, if they pass, then they are not String
(or text) based values...
Verify each character within the String
to see if it contains more than just digits, using something like Character#isLetter
Use a regular expression to determine if the value contain other content other than numbers.
Upvotes: 2