简体   繁体   English

如何将负整数转换为正整数

[英]How to convert the negative integer to positive

String v1 = lbl_READING_NUMBER.getText();


int a = Integer.parseInt(jLabel_PREVIOUS_READ.getText());

int b = Integer.parseInt(jLabel_PRESENT_READ.getText());

int cm = a-b;

try{

    String sql = "UPDATE reading SET Cubic_meter=' "+cm+" ' WHERE Reading_Number=' "+v1+"' ";

    ps = conn.prepareStatement(sql);

    rs=ps.executeUpdate();
}
catch(Exception e){

    JOptionPane.showMessageDialog(null, e);

}

This code display negative Cubic_meter column in my database, want to have a positive Cubic_meter even if the jLabel_PREVIOUS_READ.getText() is lesser than jLabel_PRESENT_READ.getText() . 此代码在我的数据库中显示负的Cubic_meter列,即使jLabel_PREVIOUS_READ.getText()小于jLabel_PRESENT_READ.getText() ,也要具有正的Cubic_meter。

It sounds like you might be looking for Math.abs : 听起来您可能正在寻找Math.abs

Returns the absolute value of an int value. 返回int值的绝对值。 If the argument is not negative, the argument is returned. 如果参数不为负,则返回参数。 If the argument is negative, the negation of the argument is returned. 如果参数为负,则返回参数取反。

(There are also versions for other types — long , float , double ...) (还有其他类型的版本longfloatdouble ...)

There's an important caveat: 有一个重要警告:

Note that if the argument is equal to the value of Integer.MIN_VALUE , the most negative representable int value, the result is that same value, which is negative. 请注意,如果参数等于Integer.MIN_VALUE的值(最负的可表示int值),则结果是相同的值,该值为负。

Do Math.abs like TJ Crowder suggested, but also do 像TJ Crowder建议的那样做Math.abs,但也可以

catch NumberFormatException when parsing the input 解析输入时捕获NumberFormatException

Change your SQL statement to use bound variables, like this 更改您的SQL语句以使用绑定变量,如下所示

    String sql = "UPDATE reading SET Cubic_meter=? WHERE Reading_Number= ?";
    ps = conn.prepareStatement(sql);
    ps.setInt(1, cm); // assuming always positive
    ps.setInt(2, v1);

http://en.wikipedia.org/wiki/Prepared_statement http://en.wikipedia.org/wiki/Prepared_statement

Using bound variable is a good practice to guard against SQL injection. 使用绑定变量是防止SQL注入的好习惯。

Can you use this? 你能用这个吗?

 value=value*-1; //simply multiply by -1. 

You can also set a condition to check if the value is negative with an if statement such as. 您还可以使用if语句设置条件来检查该值是否为负。

 if(value<0)
   value=value*-1; //simply multiply by -1. 

Try this: 尝试这个:

int cm = a-b;
int cm2 = cm*(-1);

try{

    String sql = "UPDATE reading SET Cubic_meter=' "+cm2+" ' WHERE Reading_Number=' "+v1+"' ";

    ps = conn.prepareStatement(sql);

    rs=ps.executeUpdate();
}
catch(Exception e){

    JOptionPane.showMessageDialog(null, e);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM