I have to do a job and I have a point that I don't know exactly if it would turn out well or not.
I tell you it is a card game and I have an attribute of the card class that is the year of creation. to not mess around I have put it as String.
Now in the SET I want to verify that the string that I enter is numeric and 4 digits.
About the numerical chain I had thought something like this
public void setAñoCreacion(String añoCreacion) {
if(Integer.parseInt(añoCreacion)
this.añoCreacion = añoCreacion
}
}
But it doesn't admit me because it says that it can't be passed to boolean I don't understand why it isn't either it's numeric or it isn't. Thank you for helping me.
In the statement
if (condición)
, condition must always be a piece of code equivalent to a boolean.In your code, you use the function
parseInt
for the condition:The function
parseInt
returns a data of type int, that's why you get the error:The if expects a boolean and you are passing it an int . There are several ways to fix this problem, one of them could be to use the
StringUtils.isNumeric
.To check that the year has 4 digits, I suggest you use the .length() function of String, and finally the code would look like this:
To use the isNumeric function, you have to add the corresponding library.
Hello, to make the verification of both things more effective, I leave you the following example:
I hope it helps you, greetings.
You could check it with a regular expression:
On the other hand, I recommend you read why it is not good to use
ñ
or accents in the source code .An easy way following what you were using is to convert to integer and check the number of digits based on the value:
You can also add as an additional condition that it be less than 10000 in case there could be more than 4 digits.
You can leave the setter as follows:
And do your checks elsewhere, such as in the keyPressed event, there you can simply check if the pressed key is numeric, so you guarantee that the value obtained is numeric, then with a condition you verify that the value is 4 digits and you send the setter
To check the length you can use the
length
String method.That is if I would not do these checks on the set but before.