java – Know if a string is numeric

Question:

I have a job to do and I have a point that I don't know exactly if it would work out or not.

I tell you it is a card game and I have an attribute of the letter class that is the year of creation. I have put it as String so as not to be fussed over.

Now in the SET I want to verify that the string that I enter is numeric and has 4 digits.

The number string thing 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 numeric 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 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 an int to it . There are several ways to solve 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 String's .length () function, 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;
Scroll to Top