Java 检查整数是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38423256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:19:10  来源:igfitidea点击:

Check if a Integer is empty

javajdbc

提问by Bogdan

I want to check if a Integervalue is empty. The value for Integeris completed in a form. Here is my code.

我想检查一个Integer值是否为空。的值以Integer表格形式填写。这是我的代码。

Here the value is introduced:

这里引入了值:

<input name="varsta" placeHolder="Varsta:" type="text" data-constraints='@NotEmpty @Required @AlphaSpecial'> <br/><br/>

Now I want to check if there are data introduced or not.

现在我想检查是否有数据引入。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    Integer varsta = Integer.parseInt(request.getParameter("varsta"));
    request.getSession().setAttribute("varsta", varsta);

    try {
        DBConnection connection = new DBConnection();
        Connection con = connection.Connect();

        PreparedStatement ps = con.prepareStatement(
            "insert into user(Nume,Prenume,E_mail,Parola,Varsta,Sex,Greutate,Inaltime,Nivel_activitate,Calcul_calorii)" + 
            "values ('"+nume+"','"+prenume+"','"+email1+"','"+parola+"','"+varsta+"','"+sex+"','"+greutate+"','"+inaltime+"','"+activitate+"','"+calorii+"')"
        );

        if (varsta == null && "".equals(varsta)) {
            String message = "Va rugam completati cu atentie TOATE campurile!";
            request.setAttribute("message", message);
            request.getRequestDispatcher("/inregistrare.jsp").forward(request, response);           
        } else {
           int i = ps.executeUpdate();

           if (i > 0) {
              request.getRequestDispatcher("/preferinte.jsp").forward(request, response);
           }
        }
        ps.close();
        con.close();         
    } catch(Exception se) {
        se.printStackTrace();
    }
}       

is not working.

不管用。

Could anyone help me?

有人可以帮助我吗?

采纳答案by Vladimir Vagaytsev

Class Integeris just an wrapper on top of primitive inttype. So it can either be nullor store a valid integer value. There is no obvious "empty" definition for it.

Integer只是原始int类型之上的包装器。所以它可以是null或存储一个有效的整数值。它没有明显的“空”定义。

If you just compare Integeragainst empty String, you''ll get falseas a result. Always. See Integer.equals(Object o)implementation:

如果您只是Integer与 empty进行比较String,您就会得到false结果。总是。见Integer.equals(Object o)实现:

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

First of all, you can get a NumberFormatExceptionduring parsing integer in the line:

首先,您可以NumberFormatException在行中解析整数期间获得一个:

Integer varsta = Integer.parseInt(request.getParameter("varsta"));

And you are getting it, since For input string: ""looks like a NumberFormatExpectionmessage.

你明白了,因为For input string: ""看起来像一条NumberFormatExpection消息。

In your example you should either check whether the "varsta"attribute value is a number (assume it's a string) and then parse it, or parse it as is and catch NumberFormatExceptionthat Integer.parseInt()throws on incorrect argument.

在您的例子您应该检查是否"varsta"属性值是一个数(假设它是一个字符串),然后分析它,或解析它是和捕获NumberFormatException的是Integer.parseInt()不正确的说法抛出。

First solution:

第一个解决方案:

Integer varsta = null;
String varstaStr = request.getParameter("varsta"); // read string 'varsta' field
if (varstaStr != null && varstaStr.matches("\d+")) { // null-check and regex check to make sure the string contains only digits
     varsta = Integer.parseInt(varstaStr);
}

Second solution:

第二种解决方案:

Integer varsta = null;
String varstaStr = request.getParameter("varsta"); // read string 'varsta' field
try {
    varsta = Integer.parseInt(varsta);
} catch (NumberFormatException e) {
    // handle error
}

After this, you have one more problem in the line:

在此之后,您还有一个问题:

if(varsta == null && "".equals(varsta)){

The varstareference has type Integerhere, so "".equals(varsta)will always return false:

varsta参考具有类型Integer在这里,所以"".equals(varsta)总是返回false

(varsta == null && "".equals(varsta)) = [assume varsta is null] =
((null) == null && "".equals(null)) = (true && false) = false

Replace

代替

if(varsta == null && "".equals(varsta)){

with

if(varsta == null){

This should help you.

这应该对你有帮助。

P.S.If you use Java of version 7 or higher, consider use try-with-resourcesto manage Connectionand PreparedStatement.

PS如果你使用Java 7或更高版本,可以考虑使用try-with-resources来管理ConnectionPreparedStatement

回答by YCF_L

If you want to check if your field is empty or not than you can use that:

如果您想检查您的字段是否为空,则可以使用:

if (!request.getParameter("varsta").equals("")) {
    System.out.println("not empty");
} else {
    System.out.println("Empty");
}

But if you want to get the value so you should to be carful:

但是如果你想获得价值,那么你应该小心:

try {
    if (!request.getParameter("varsta").equals("")) {
        System.out.println("not empty");
        Integer varsta = new Integer(request.getParameter("varsta"));
    } else {
        System.out.println("Exmpty");
    }
} catch (NumberFormatException e) {
    System.out.println("Number is not correct");
}

what if request.getParameter("varsta") = "4558ez"? this can make a problem.

万一request.getParameter("varsta") = "4558ez"呢?这可能会产生问题。