For one thing you should be using the Character
methods for doing this rather than a home grown solution, namely Character.isDigit()
for checking validity and Character.digit()
for getting a value:
char c = ...
if (Character.isDigit(c)) {
// it's a digit
}
int value = Character.digit(c, 10);
Why you're getting this warning is explained by 5.6.2 Binary Numeric Promotion from the Java Language Specification:
When an operator applies binary
numeric promotion to a pair of
operands, each of which must denote a
value of a numeric type, the following
rules apply, in order, using widening
conversion (§5.1.2) to convert
operands as necessary:
- If either operand is of type
double
, the other is converted to
double
.
- Otherwise, if either operand is of type
float
, the other is converted
to float
.
- Otherwise, if either operand is of type
long
, the other is converted to
long
.
- Otherwise, both operands are converted to type
int
.
So what's happening is that when you do the subtraction both arguments are being promoted to int
s. The result is an int
. When you try and assign that int
to a char
there is a possible loss of precision (32 bit signed to 16 bit unsigned).
An alternative validation technique is simply to use a regular expression:
if (s.matches("\\d\\d-\\d\\d")) {
// it's ##-##
}
or, if you need to grab the groups:
Pattern p = Pattern.compile("(\\d\\d)-(\\d\\d)");
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println(m.group(1)); // first group
System.out.println(m.group(1)); // second group
}