Is there a method that parses int or returns 0 if unable to do so?

I am constantly having to write something like this in different places and projects.

int appointmentId =  Integer.parseInt(StringUtils.isNotEmpty(request.getParameter
("appointmentId")) ? request.getParameter("appointmentId"): "0");

Is there a common class that returns parsed int or 0 or something you specify as default return value?

Answers


Apache Commons' NumberUtils.toInt() returns 0 if the conversion fails.

(And another that lets you specify the default value on conversion failure.)


Just catch the NumberFormatException and return 0? It wouldn't be useful to have such a method in the Java API. I mean, with your method you never know if there was an error or not if the method returns 0. So it's only logically that you have to do something like this by yourself.

Something like:

public int getInt(String myInt) {
    int i;
    try {
        i = Integer.parseInt(myInt);
    } catch(NumberFormatException ex) {
        i = 0;
    }
    return i;
}

Need Your Help

IntelliJ: Classes from imported jar not visible inside packages

java ide intellij-idea

I added external jar file(stdlib.jar on picture) to my project in IntelliJ(12.1.4), but when I want to use some static methods from it in created package(ChapterOne) it can't resolve it. However it...

working with out of range integers in java

java rsa

Working on a project dealing with RSA encyption and decryption and part of it is working with this number

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.