-2
final EditText ed7 = (EditText)findViewById(R.id.Recycleweight);
final EditText ed8 = (EditText)findViewById(R.id.Nonweight);
final EditText ed11 = (EditText)findViewById(R.id.totalweight);

recy_wt=ed7.getText().toString();
nonrec_wt=ed8.getText().toString();
total_wt=ed11.getText().toString();

int rec = Integer.parseInt(recy_wt);
int nrec = Integer.parseInt(nonrec_wt);
ed11.setText(String.valueOf(rec + nrec));

The input I am giving is,ed7=10kg and ed8=20kg,and it will be displayed in ed11 as 30kg,but the app is unfortunately stopping. If I am not writing 'kg',it is correctly displaying the totalwt. But I want to display 'kg' in the answer.

Mr.7
  • 2,292
  • 1
  • 20
  • 33
KiranB
  • 13
  • 6

4 Answers4

1

There is already a solution here (can't flag as duplicate) Find and extract a number from a string

Extract the digit part from the string and then parse it to an integer

Community
  • 1
  • 1
Aenima
  • 155
  • 1
  • 13
0

Try this out

String regexp = "/^[0-9]+kg$/g"; //It accepts only '<number><kg>' format
int weight = 0;
if (recy_wt.matches(regexp) && nonrec_wt.matches(regex)) {
    //It's valid input
    Scanner scan = new Scanner(recy_wt);
    weight = Integer.parseInt(scan.findInLine("\\d+(\\.\\d+)?"));
    Scanner scan = new Scanner(nonrec_wt);
    weight += Integer.parseInt(scan.findInLine("\\d+(\\.\\d+)?"));
}

ed11.setText(String.valueOf(weight + "Kg"));
Mr.7
  • 2,292
  • 1
  • 20
  • 33
0

If the only possible unit is kg, then try like this

final EditText ed7 = (EditText)findViewById(R.id.Recycleweight);
final EditText ed8 = (EditText)findViewById(R.id.Nonweight);
final EditText ed11 = (EditText)findViewById(R.id.totalweight);

int weight = 0;

recy_wt=ed7.getText().toString();
nonrec_wt=ed8.getText().toString();

recy_wt = recy_wt.replace("kg","");
nonrec_wt = nonrec_wt.replace("kg","");

weight += Integer.parseInt(recy_wt) + Integer.parseInt(nonrec_wt);

ed11.setText(weight + "kg");
Mr.7
  • 2,292
  • 1
  • 20
  • 33
-1

This will work:-

recy_wt=ed7.getText().toString();
nonrec_wt=ed8.getText().toString();

String n=recy_wt.replace("kg","");
String n1=nonrec_wt.replace("kg","");

weight += Integer.parseInt(n) + Integer.parseInt(n1);
ed11.setText(weight + "kg");

storing the replaced one in a string and then converting to int will help.

KiranB
  • 13
  • 6