Question:
I have to do some work 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 does not admit me because it says that it cannot be passed to boolean I do not understand why it is not or it is numerical or it is not. Thank you for helping me.
Answer:
In the if (condición)
, condition must always be a piece of code equivalent to a boolean.
In your code, you use the parseInt
function for the condition:
if (Integer.parseInt(añoCreacion)) {
this.añoCreacion = añoCreacion;
}
The parseInt
function returns a data of type int, that's why you get the error:
Type mismatch: cannot convert from int to boolean
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
function.
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:
if (StringUtils.isNumeric(añoCreacion) && añoCreacion.length() == 4) {
this.añoCreacion = añoCreacion;
}
To use the isNumeric function, you have to add the corresponding library.
import org.apache.commons.lang3.StringUtils;