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));
我给的输入是,ed7 = 10kg,ed8 = 20kg,它将显示在ed11中 为30公斤,但不幸的是停止了应用程序。 如果我不写'公斤',它正确显示总重量。 但我想展示' kg'在答案中。
答案 0 :(得分:1)
此处已有解决方案(无法标记为重复) Find and extract a number from a string
从字符串中提取数字部分,然后将其解析为整数
答案 1 :(得分:0)
试试这个
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"));
答案 2 :(得分:0)
如果唯一可能的单位是kg
,那么请尝试这样
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");
答案 3 :(得分:-1)
这将有效: -
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");
将替换的一个存储在字符串中,然后转换为int将有所帮助。