简体   繁体   中英

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() .

It sounds like you might be looking for Math.abs :

Returns the absolute value of an int value. 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 ...)

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.

Do Math.abs like TJ Crowder suggested, but also do

catch NumberFormatException when parsing the input

Change your SQL statement to use bound variables, like this

    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

Using bound variable is a good practice to guard against SQL injection.

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(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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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