-5

Am having two string contaning integer values how can i subtract this to string.

 String addquantity = quantity1.getText().toString();
 String subquantity = quantity2.getText().toString();
 int final_ = Integer.parseInt(addquantity) - Integer.parseInt(subquantity);

I tried many methods but its showing error , help me to subtract the value in string.

janos
  • 120,954
  • 29
  • 226
  • 236
Sivakumar S
  • 129
  • 2
  • 3
  • 16

3 Answers3

1

Maybe your EditTexts are not initialized, you need something like quantity1 = (EditText) findViewById(R.id.YOUR_EDIT_TEXT_ID) for both.

Evin1_
  • 12,292
  • 9
  • 45
  • 47
Manuel Pamplona
  • 217
  • 1
  • 5
0

Check what you are passing...check my example.

package general;

public class TestNumberFormat {

    public static void main(String[] args){
     String addquantity = "40";
     String subquantity = "30";
     int final_ = Integer.parseInt(addquantity) - Integer.parseInt(subquantity);
     System.out.println("PRINT :" + final_);

     String addquantity1 = "D40";
     String subquantity1 = "D30";
     int final1_ = Integer.parseInt(addquantity1) - Integer.parseInt(subquantity1);
     System.out.println("PRINT :" + final1_);

  }
}

Output:

PRINT :10

Exception in thread "main" java.lang.NumberFormatException: For input string: "D40"  
at       java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)  
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at general.TestNumberFormat.main(TestNumberFormat.java:13)
Suparna
  • 1,132
  • 1
  • 8
  • 20
0

Maybe you got an space in your string. Use following

String addquantity = quantity1.getText().toString().trim();
String subquantity = quantity2.getText().toString().trim();