The conversion between strings and numbers is a problem that we are bound to encounter in our project because the value of the variable we get from the user interface is definitely a string.
So, what we often have to do in the project is: first, you need to check the user's input to determine whether the user's input is a number; second, if so, we need to further convert it to numbers to facilitate our calculations.
In the Java language, we want to determine whether a string is a number, there are basically two methods, the first is directly to the conversion, if there are exception thrown, then the string is not the number we need. Here is a section of code that determines whether a string is an integer number:
public static boolean isInt(String str)
{
try
{
Integer.parseInt(str);
return true;
}
catch(Exception e)
{
return false;
}
}
Similarly, I would like to judge whether a string is float, double, or Boolean, and can be judged using this method.
The second approach is to judge by regular expressions, where no examples are given.
All in all, both of these methods require us to give the code to judge.
In the groovy language, the system has APIs to help us do this directly, quite simply. For example, if we need to determine whether a string is an int, we just need to write the following code:
def num = '23'
println num.isInteger()
The results of the operation are:
True
If this is the following code:
def num1 = '2.3'
println num1.isInteger()
The result of the run is:
False