简体   繁体   中英

Sum of multiple selected checkboxes in JAVA

If I use the "+ " sign it will just concatenate the values, but I need to find the mathematical values. I need to insert the quantity of a product. How to find the sum when multiple checkboxes are selected? I have tried this which concatenates.. Also the values need to go into the database, it is working with the concatenated values..

                 if(chckbx1.isSelected()){
                    qty= chckbx1.getText();
                    chckbx1.setSelected(true);
             }

             if(chckbx1.isSelected() && chckbx5.isSelected()){
                    qty= chckbx1.getText() + chckbx5.getText();
                    chckbx5.setSelected(true);
                    chckbx1.setSelected(true);
             }

您需要使用 Double.parseDouble() 将其解析为 Double

qty= (Double.parseDouble(chckbx1.getText()) + Double.parseDouble(chckbx5.getText())) + "";

您可以使用 Integer.parseInt() 将其解析为 Integer

qty= (Integer.parseInt(chckbx1.getText()) + Integer.parseInt(chckbx5.getText())) + "";

Yes, Using the + operator on Strings concatenates them.

So, you need to convert the Strings to numbers.
Depending upon what type of numbers the Strings contain (real or integer), you may parse them to numbers in one of the following ways:

  • qty= ""+ ( Integer.parseInt(chckbx1.getText()) + Integer.parseInt(chckbx5.getText()) );
  • qty= ""+ ( Double.parseDouble(chckbx1.getText()) + Double.parseDouble(chckbx5.getText()) );

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